You can use the "User-Defined Language" option available at the notepad++. You do not need to do the xml-based hacks, where the formatting would be available only in the searched window, with the formatting rules.
Sample for your reference here.
You can just go to nodejs.org and download the newest package. It will update appropriately for you. NPM will be updated as well.
Its because of wrong path provided. It may be that the url contains space and if the case url has to be properly constructed.
The correct url should be in the format with file name included like "http://server name/document library name/new file name"
So if report.xlsx is the file that has to be uploaded at "http://server name/Team/Dev Team" then path comes out to be is "http://server name/Team/Dev Team/report.xlsx". It contains space so it should be reconstructed as "http://server name/Team/Dev%20Team/report.xlsx" and should be used.
I use BC3 for my git diff, but I'd also add vscode to the list of useful git diff tools. Some users prefer vscode over vs ide experience.
git config --global diff.tool vscode
git config --global difftool.vscode.cmd "code --wait --diff $LOCAL $REMOTE"
I had the same issue and along with removing the node_modules and reinstalling I needed to remove package-lock.json first.
I tend to agree with split suggestion.
Ive created a "tester" for your problem in perl
#!/usr/bin/perl -w
@strings = ( "1.2.3", "1.2.*", "1.*","*" );
%regexp = ( svrist => qr/(?:(\d+)\.(\d+)\.(\d+)|(\d+)\.(\d+)|(\d+))?(?:\.\*)?/,
onebyone => qr/^(\d+\.)?(\d+\.)?(\*|\d+)$/,
greg => qr/^(\*|\d+(\.\d+){0,2}(\.\*)?)$/,
vonc => qr/^((?:\d+(?!\.\*)\.)+)(\d+)?(\.\*)?$|^(\d+)\.\*$|^(\*|\d+)$/,
ajb => qr/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/,
jrudolph => qr/^(((\d+)\.)?(\d+)\.)?(\d+|\*)$/
);
foreach my $r (keys %regexp){
my $reg = $regexp{$r};
print "Using $r regexp\n";
foreach my $s (@strings){
print "$s : ";
if ($s =~m/$reg/){
my ($main, $maj, $min,$rev,$ex1,$ex2,$ex3) = ("any","any","any","any","any","any","any");
$main = $1 if ($1 && $1 ne "*") ;
$maj = $2 if ($2 && $2 ne "*") ;
$min = $3 if ($3 && $3 ne "*") ;
$rev = $4 if ($4 && $4 ne "*") ;
$ex1 = $5 if ($5 && $5 ne "*") ;
$ex2 = $6 if ($6 && $6 ne "*") ;
$ex3 = $7 if ($7 && $7 ne "*") ;
print "$main $maj $min $rev $ex1 $ex2 $ex3\n";
}else{
print " nomatch\n";
}
}
print "------------------------\n";
}
Current output:
> perl regex.pl
Using onebyone regexp
1.2.3 : 1. 2. 3 any any any any
1.2.* : 1. 2. any any any any any
1.* : 1. any any any any any any
* : any any any any any any any
------------------------
Using svrist regexp
1.2.3 : 1 2 3 any any any any
1.2.* : any any any 1 2 any any
1.* : any any any any any 1 any
* : any any any any any any any
------------------------
Using vonc regexp
1.2.3 : 1.2. 3 any any any any any
1.2.* : 1. 2 .* any any any any
1.* : any any any 1 any any any
* : any any any any any any any
------------------------
Using ajb regexp
1.2.3 : 1 2 3 any any any any
1.2.* : 1 2 any any any any any
1.* : 1 any any any any any any
* : any any any any any any any
------------------------
Using jrudolph regexp
1.2.3 : 1.2. 1. 1 2 3 any any
1.2.* : 1.2. 1. 1 2 any any any
1.* : 1. any any 1 any any any
* : any any any any any any any
------------------------
Using greg regexp
1.2.3 : 1.2.3 .3 any any any any any
1.2.* : 1.2.* .2 .* any any any any
1.* : 1.* any .* any any any any
* : any any any any any any any
------------------------
Use Apache Common IO's FileUtils
:
import org.apache.commons.io.FileUtils
FileUtils.copyURLToFile(url, f);
The method downloads the content of url
and saves it to f
.
Try This below method code to get the distance in meter between two location, hope it will help for you
public static double distance(LatLng start, LatLng end){
try {
Location location1 = new Location("locationA");
location1.setLatitude(start.latitude);
location1.setLongitude(start.longitude);
Location location2 = new Location("locationB");
location2.setLatitude(end.latitude);
location2.setLongitude(end.longitude);
double distance = location1.distanceTo(location2);
return distance;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
Using imagemagick, you can try:
convert page.png page.pdf
Or for multiple images:
convert page*.png mydoc.pdf
mysqli_select_db()
should have 2 parameters, the connection link and the database name -
mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));
Using mysqli_error
in the die statement will tell you exactly what is wrong as opposed to a generic error message.
Your hash is already binary and ready to be used with your database.
However you must need to convert it into a format the database column definition expects.
Any string in PHP (until 5.3) is a binary string. That means it contains only binary data.
However because of backwards compatiblity with PHP 6 you can already cast your string explicitly as binary:
$string = 'my binary string';
$binary = b'my binary string';
But that is merely for compatibility reasons, in your code you can just do:
$string = $binary; // "convert" binary string into string
$binary = $string // "convert" string into binary string
Because it's the same. The "convert" is superfluous.
Allow only numbers in TextBox (Restrict Alphabets and Special Characters)
/*code: 48-57 Numbers
8 - Backspace,
35 - home key, 36 - End key
37-40: Arrow keys, 46 - Delete key*/
function restrictAlphabets(e){
var x=e.which||e.keycode;
if((x>=48 && x<=57) || x==8 ||
(x>=35 && x<=40)|| x==46)
return true;
else
return false;
}
Just single if conditions
<select name="category_type[]" id="category_type" class="select2 m-b-10 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose" tooltip="Select Category Type">
@foreach ($categoryTypes as $categoryType)
<option value="{{ $categoryType->id }}"
**@if(in_array($categoryType->id,
request()->get('category_type')??[]))selected="selected"
@endif**>
{{ ucfirst($categoryType->title) }}</option>
@endforeach
</select>
You can use PropertyConfigurator
to load your log4j.properties wherever it is located in the disk.
Example:
Logger logger = Logger.getLogger(this.getClass());
String log4JPropertyFile = "C:/this/is/my/config/path/log4j.properties";
Properties p = new Properties();
try {
p.load(new FileInputStream(log4JPropertyFile));
PropertyConfigurator.configure(p);
logger.info("Wow! I'm configured!");
} catch (IOException e) {
//DAMN! I'm not....
}
If you have an XML Log4J configuration, use DOMConfigurator instead.
Treating the database as just a storage mechanism (i.e. glorified collections library) and hence subordinate to their application (ignoring other applications which share the data)
With Tomcat 7, you can add the StuckThreadDetectionValve which will enable you to identify threads that are "stuck". You can set-up the valve in the Context element of the applications where you want to do detecting:
<Context ...>
...
<Valve
className="org.apache.catalina.valves.StuckThreadDetectionValve"
threshold="60" />
...
</Context>
This would write a WARN entry into the tomcat log for any thread that takes longer than 60 seconds, which would enable you to identify the applications and ban them because they are faulty.
Based on the source code you may be able to write your own valve that attempts to stop the thread, however this would have knock on effects on the thread pool and there is no reliable way of stopping a thread in Java without the cooperation of that thread...
The proper way to do it is using the ng-options
directive. The HTML would look like this.
<select ng-model="selectedTestAccount"
ng-options="item.Id as item.Name for item in testAccounts">
<option value="">Select Account</option>
</select>
JavaScript:
angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
method: 'GET',
url: '/Admin/GetTestAccounts',
data: { applicationId: 3 }
}).success(function (result) {
$scope.testAccounts = result;
});
});
You'll also need to ensure angular is run on your html and that your module is loaded.
<html ng-app="test">
<body ng-controller="DemoCtrl">
....
</body>
</html>
This is deprecated:
as.data.frame(my_table)
Instead use this package:
library("quanteda")
convert(my_table, to="data.frame")
Try this
q = Session.query(
User, Document, DocumentPermissions,
).filter(
User.email == Document.author,
).filter(
Document.name == DocumentPermissions.document,
).filter(
User.email == 'someemail',
).all()
One solution to this problem is to use the Handler.postDelayed() method. Some Google training materials suggest the same solution.
@Override
public void onClick(View v) {
my_button.setBackgroundResource(R.drawable.icon);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
my_button.setBackgroundResource(R.drawable.defaultcard);
}
}, 2000);
}
However, some have pointed out that the solution above causes a memory leak because it uses a non-static inner and anonymous class which implicitly holds a reference to its outer class, the activity. This is a problem when the activity context is garbage collected.
A more complex solution that avoids the memory leak subclasses the Handler
and Runnable
with static inner classes inside the activity since static inner classes do not hold an implicit reference to their outer class:
private static class MyHandler extends Handler {}
private final MyHandler mHandler = new MyHandler();
public static class MyRunnable implements Runnable {
private final WeakReference<Activity> mActivity;
public MyRunnable(Activity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
public void run() {
Activity activity = mActivity.get();
if (activity != null) {
Button btn = (Button) activity.findViewById(R.id.button);
btn.setBackgroundResource(R.drawable.defaultcard);
}
}
}
private MyRunnable mRunnable = new MyRunnable(this);
public void onClick(View view) {
my_button.setBackgroundResource(R.drawable.icon);
// Execute the Runnable in 2 seconds
mHandler.postDelayed(mRunnable, 2000);
}
Note that the Runnable
uses a WeakReference to the Activity, which is necessary in a static class that needs access to the UI.
SELECT date_column_name FROM table_name WHERE EXTRACT(YEAR FROM date_column_name) = 2020
1 use command
show create table test.location
Another solution you can use is SQL Developer.
With it, you have the ability to import from a csv file (other delimited files are available).
Just open the table view, then:
You have the option to have SQL Developer do the inserts for you, create an sql insert script, or create the data for a SQL Loader script (have not tried this option myself).
Of course all that is moot if you can only use the command line, but if you are able to test it with SQL Developer locally, you can always deploy the generated insert scripts (for example).
Just adding another option to the 2 already very good answers.
<html:form name="Form" type="abc" action="abc.do" method="get" onsubmit="return false;">
method="get"
- resolves the problem.
if method="post"
then only warning comes.
Had the same issue and I 'Compiled VBA Project' which identified an error. After correction and compiling, the macros worked.
My full example is here, but I will provide a summary below.
Layout
Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).
Make the swift file the xib file's owner.
Add the following code to the .swift file and hook up the outlets and actions from the .xib file.
import UIKit
class ResuableCustomView: UIView {
let nibName = "ReusableCustomView"
var contentView: UIView?
@IBOutlet weak var label: UILabel!
@IBAction func buttonTap(_ sender: UIButton) {
label.text = "Hi"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
guard let view = loadViewFromNib() else { return }
view.frame = self.bounds
self.addSubview(view)
contentView = view
}
func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
}
Use it
Use your custom view anywhere in your storyboard. Just add a UIView
and set the class name to your custom class name.
For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.
MyCustomClass.swift
MyCustomClass.xib
File's Owner
of the .xib file to be your custom class (MyCustomClass
)class
value (under the identity Inspector
) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.Assistant Editor
.
Connections Inspector
you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass
), but rather reference File's Owner
. Since File's Owner
is specified to be your custom class, the outlets will hook up and work propery. NibLoadable
protocol referenced below.
.swift
file name is different from your .xib
file name, then set the nibName
property to be the name of your .xib
file.required init?(coder aDecoder: NSCoder)
and override init(frame: CGRect)
to call setupFromNib()
like the example below.MyCustomClass
).Here is the protocol you will want to reference:
public protocol NibLoadable {
static var nibName: String { get }
}
public extension NibLoadable where Self: UIView {
public static var nibName: String {
return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
}
public static var nib: UINib {
let bundle = Bundle(for: Self.self)
return UINib(nibName: Self.nibName, bundle: bundle)
}
func setupFromNib() {
guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
}
}
And here is an example of MyCustomClass
that implements the protocol (with the .xib file being named MyCustomClass.xib
):
@IBDesignable
class MyCustomClass: UIView, NibLoadable {
@IBOutlet weak var myLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupFromNib()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupFromNib()
}
}
NOTE: If you miss the Gotcha and set the class
value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS
error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder)
method which then calls Self.nib.instantiate
and calls the init
again.
However, starting in Java SE 8, a local class can access local variables and parameters of the >enclosing block that are final or effectively final.
This didn't start on Java 8, I use this since long time. This code used (before java 8) to be legal:
String str = ""; //<-- not accesible from anonymous classes implementation
final String strFin = ""; //<-- accesible
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String ann = str; // <---- error, must be final (IDE's gives the hint);
String ann = strFin; // <---- legal;
String str = "legal statement on java 7,"
+"Java 8 doesn't allow this, it thinks that I'm trying to use the str declared before the anonymous impl.";
//we are forced to use another name than str
}
);
This code work for me:
fetch('http://localhost:8080')
.then(response => response.json())
.then(json => {
this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})
Other posts here have made it clear that the result is an "empty" IQueryable, which ToList() will correctly change to be an empty list etc.
Do be careful with some of the operators, as they will throw if you send them an empty enumerable. This can happen when you chain them together.
Simply replacing the src
attribute of the iframe element was not satisfactory in my case because one would see the old content until the new page is loaded. This works better if you want to give instant visual feedback:
var url = iframeEl.src;
iframeEl.src = 'about:blank';
setTimeout(function() {
iframeEl.src = url;
}, 10);
In the pop up
You end up with a big line. Then
In the pop up
So you end up with lines that end by dot
And if you have to do the same process lots of times
https://github.com/mattt/TTTAttributedLabel
That's definitely what you need. You can also apply attributes for your label, like underline, and apply different colors to it. Just check the instructions for clickable urls.
Mainly, you do something like the following:
NSRange range = [label.text rangeOfString:@"me"];
[label addLinkToURL:[NSURL URLWithString:@"http://github.com/mattt/"] withRange:range]; // Embedding a custom link in a substring
Go to project folder in command prompt or in Project Terminal.
Run cmd : ng g c componentname
While you can, as others have noted here, put a DIV inside a TD (not as a direct child of TABLE), I strongly advise against using a DIV as a child of a TD. Unless, of course, you're a fan of headaches.
There is little to be gained and a whole lot to be lost, as there are many cross-browser discrepancies regarding how widths, margins, borders, etc., are handled when you combine the two. I can't tell you how many times I've had to clean up that kind of markup for clients because they were having trouble getting their HTML to display correctly in this or that browser.
Then again, if you're not fussy about how things look, disregard this advice.
maybe this help :
declare
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'
set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + '''
'
exec sp_executesql @statement;
this is same as below :
select @text1 + ' beautifull ' + @text2
The reason for this warning is that const in c doesn't mean constant. It means "read only". So the value is stored at a memory address and could potentially be changed by machine code.
For getting selected value use
$('#dropDownId').val();
and for getting selected item text use this line:
$("#dropDownId option:selected").text();
I simply use the command
git clean -n *.orig
check to make sure only file I want remove are listed then
git clean -f *.orig
I think you may use the callback from a JSONP request or maybe just the pure JSON data using an external service but based on the output of javascript location.host
that way:
$.getJSON( "//freegeoip.net/json/" + window.location.host + "?callback=?", function(data) {
console.warn('Fetching JSON data...');
// Log output to console
console.info(JSON.stringify(data, null, 2));
});
I'll use this code for my personal needs, as first I was coming on this site for the same reason.
You may use another external service instead the one I'm using for my needs. A very nice list exist and contains tests done here https://stackoverflow.com/a/35123097/5778582
For my case, it because I use fish. if I not start fish, just type nvm will no error now.
You can do it in the web.config
<httpProtocol>
<customHeaders>
<add name="X-UA-Compatible" value="IE=7"/>
</customHeaders>
</httpProtocol>
I have better results with this over the above solutions. Not sure why this wasn't given as a solution. :)
You can use Case
expression for returning a boolean
in your select query like below.
@Query("SELECT CASE WHEN count(e) > 0 THEN true ELSE false END FROM MyEntity e where e.my_column = ?1")
I also had this problem. If you also have Visual Studio installed with the Python extension, the system will want to use Studio's version of Python. Set the Environment Path to the version in Studio's Shared folder. For me, that was:
C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\
After that, run
python -m pip install pylint
from a command prompt with Administrator rights.
Seriously, just don't use jQuery for this. disabled
is a boolean property of form elements that works perfectly in every major browser since 1997, and there is no possible way it could be simpler or more intuitive to change whether or not a form element is disabled.
The simplest way of getting a reference to the checkbox would be to give it an id
. Here's my suggested HTML:
<input type="hidden" name="chk0" value="">
<input type="checkbox" name="chk0" id="chk0_checkbox" value="true" disabled>
And the line of JavaScript to make the check box enabled:
document.getElementById("chk0_checkbox").disabled = false;
If you prefer, you can instead use jQuery to get hold of the checkbox:
$("#chk0_checkbox")[0].disabled = false;
You could follow a solution similar to "How do I force “git pull” to overwrite local files?":
git fetch --all
git reset --hard origin/abranch
git checkout $branch
That would involve only one fetch.
With Git 2.23+, git checkout
is replaced here with git switch
(presented here) (still experimental).
git switch -f $branch
(with -f
being an alias for --discard-changes
, as noted in Jan's answer)
Proceed even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
jQuery 'fixes up' events to account for browser differences. When it does so, you can always access the 'native' event with event.originalEvent
(see the Special Properties subheading on this page).
You can maybe do something like this with awk
awk '{outfile=sprintf("file%02d.txt",NR/5000+1);print > outfile}' yourfile
Basically, it calculates the name of the output file by taking the record number (NR) and dividing it by 5000, adding 1, taking the integer of that and zero-padding to 2 places.
By default, awk
prints the entire input record when you don't specify anything else. So, print > outfile
writes the entire input record to the output file.
As you are running on Windows, you can't use single quotes because it doesn't like that. I think you have to put the script in a file and then tell awk
to use the file, something like this:
awk -f script.awk yourfile
and script.awk
will contain the script like this:
{outfile=sprintf("file%02d.txt",NR/5000+1);print > outfile}
Or, it may work if you do this:
awk "{outfile=sprintf(\"file%02d.txt\",NR/5000+1);print > outfile}" yourfile
It's actually possible to effectively define a variable that can be used in both the SELECT, WHERE and other clauses.
A cross join doesn't necessarily allow for appropriate binding to the referenced table columns, however OUTER APPLY does - and treats nulls more transparently.
SELECT
vars.BalanceDue
FROM
Entity e
OUTER APPLY (
SELECT
-- variables
BalanceDue = e.EntityTypeId,
Variable2 = ...some..long..complex..expression..etc...
) vars
WHERE
vars.BalanceDue > 0
Kudos to Syed Mehroz Alam.
If your modulus / divisor is a known constant, and you care about performance, see this and this. A multiplicative inverse is even possible for loop-invariant values that aren't known until runtime, e.g. see https://libdivide.com/ (But without JIT code-gen, that's less efficient than hard-coding just the steps necessary for one constant.)
Never use div
for known powers of 2: it's much slower than and
for remainder, or right-shift for divide. Look at C compiler output for examples of unsigned or signed division by powers of 2, e.g. on the Godbolt compiler explorer. If you know a runtime input is a power of 2, use lea eax, [esi-1]
; and eax, edi
or something like that to do x & (y-1)
. Modulo 256 is even more efficient: movzx eax, cl
has zero latency on recent Intel CPUs (mov-elimination), as long as the two registers are separate.
The DIV
instruction (and its counterpart IDIV
for signed numbers) gives both the quotient and remainder. For unsigned, remainder and modulus are the same thing. For signed idiv
, it gives you the remainder (not modulus) which can be negative:
e.g. -5 / 2 = -2 rem -1
. x86 division semantics exactly match C99's %
operator.
DIV r32
divides a 64-bit number in EDX:EAX
by a 32-bit operand (in any register or memory) and stores the quotient in EAX
and the remainder in EDX
. It faults on overflow of the quotient.
Unsigned 32-bit example (works in any mode)
mov eax, 1234 ; dividend low half
mov edx, 0 ; dividend high half = 0. prefer xor edx,edx
mov ebx, 10 ; divisor can be any register or memory
div ebx ; Divides 1234 by 10.
; EDX = 4 = 1234 % 10 remainder
; EAX = 123 = 1234 / 10 quotient
In 16-bit assembly you can do div bx
to divide a 32-bit operand in DX:AX
by BX
. See Intel's Architectures Software Developer’s Manuals for more information.
Normally always use xor edx,edx
before unsigned div
to zero-extend EAX into EDX:EAX. This is how you do "normal" 32-bit / 32-bit => 32-bit division.
For signed division, use cdq
before idiv
to sign-extend EAX into EDX:EAX. See also Why should EDX be 0 before using the DIV instruction?. For other operand-sizes, use cbw
(AL->AX), cwd
(AX->DX:AX), cdq
(EAX->EDX:EAX), or cqo
(RAX->RDX:RAX) to set the top half to 0
or -1
according to the sign bit of the low half.
div
/ idiv
are available in operand-sizes of 8, 16, 32, and (in 64-bit mode) 64-bit. 64-bit operand-size is much slower than 32-bit or smaller on current Intel CPUs, but AMD CPUs only care about the actual magnitude of the numbers, regardless of operand-size.
Note that 8-bit operand-size is special: the implicit inputs/outputs are in AH:AL (aka AX), not DL:AL. See 8086 assembly on DOSBox: Bug with idiv instruction? for an example.
Signed 64-bit division example (requires 64-bit mode)
mov rax, 0x8000000000000000 ; INT64_MIN = -9223372036854775808
mov ecx, 10 ; implicit zero-extension is fine for positive numbers
cqo ; sign-extend into RDX, in this case = -1 = 0xFF...FF
idiv rcx
; quotient = RAX = -922337203685477580 = 0xf333333333333334
; remainder = RDX = -8 = 0xfffffffffffffff8
div dword 10
is not encodeable into machine code (so your assembler will report an error about invalid operands).
Unlike with mul
/imul
(where you should normally use faster 2-operand imul r32, r/m32
or 3-operand imul r32, r/m32, imm8/32
instead that don't waste time writing a high-half result), there is no newer opcode for division by an immediate, or 32-bit/32-bit => 32-bit division or remainder without the high-half dividend input.
Division is so slow and (hopefully) rare that they didn't bother to add a way to let you avoid EAX and EDX, or to use an immediate directly.
div and idiv will fault if the quotient doesn't fit into one register (AL / AX / EAX / RAX, the same width as the dividend). This includes division by zero, but will also happen with a non-zero EDX and a smaller divisor. This is why C compilers just zero-extend or sign-extend instead of splitting up a 32-bit value into DX:AX.
And also why INT_MIN / -1
is C undefined behaviour: it overflows the signed quotient on 2's complement systems like x86. See Why does integer division by -1 (negative one) result in FPE? for an example of x86 vs. ARM. x86 idiv
does indeed fault in this case.
The x86 exception is #DE
- divide exception. On Unix/Linux systems, the kernel delivers a SIGFPE arithmetic exception signal to processes that cause a #DE exception. (On which platforms does integer divide by zero trigger a floating point exception?)
For div
, using a dividend with high_half < divisor
is safe. e.g. 0x11:23 / 0x12
is less than 0xff
so it fits in an 8-bit quotient.
Extended-precision division of a huge number by a small number can be implemented by using the remainder from one chunk as the high-half dividend (EDX) for the next chunk. This is probably why they chose remainder=EDX quotient=EAX instead of the other way around.
If you want to go further and extract the exact information you want from the Playbook results, use JSON query language like jmespath, an example:
- name: Sample Playbook
// Fill up your task
no_log: True
register: example_output
- name: Json Query
set_fact:
query_result:
example_output:"{{ example_output | json_query('results[*].name') }}"
esp stands for "Extended Stack Pointer".....ebp for "Something Base Pointer"....and eip for "Something Instruction Pointer"...... The stack Pointer points to the offset address of the stack segment. The Base Pointer points to the offset address of the extra segment. The Instruction Pointer points to the offset address of the code segment. Now, about the segments...they are small 64KB divisions of the processors memory area.....This process is known as Memory Segmentation. I hope this post was helpful.
If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot
Swift 3 using appearance from your AppDelegate
do the following:
UITabBar.appearance().barTintColor = your_color
There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.
More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:
ping -s 1472
...)tc
iperf
Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat
or lsof
). If that number is substantial, you might:
ulimit -n
. Still, ~1000 connections (default on my system) is quite a few.iostat -x
?Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.
I hope this provides some help. You're really asking a networking question.
Replace sizeof with strlen and it should work.
I think --include
is used to include a subset of files that are otherwise excluded by --exclude
, rather than including only those files.
In other words: you have to think about include meaning don't exclude.
Try instead:
rsync -zarv --include "*/" --exclude="*" --include="*.sh" "$from" "$to"
For rsync version 3.0.6 or higher, the order needs to be modified as follows (see comments):
rsync -zarv --include="*/" --include="*.sh" --exclude="*" "$from" "$to"
Adding the -m
flag will avoid creating empty directory structures in the destination. Tested in version 3.1.2.
So if we only want *.sh files we have to exclude all files --exclude="*"
, include all directories --include="*/"
and include all *.sh files --include="*.sh"
.
You can find some good examples in the section Include/Exclude Pattern Rules of the man page
I just found this out by trying to see if my event was attached....
if you do :
item.onclick
it will return "null"
but if you do:
item.hasOwnProperty('onclick')
then it is "TRUE"
so I think that when you use "addEventListener" to add event handlers, the only way to access it is through "hasOwnProperty". I wish I knew why or how but alas, after researching, I haven't found an explanation.
I would suggest everybody, who is looking for an answer to this question, go through this "slideshow".
I couldn't understand what REST is and why it is so cool, its pros and cons, differences from SOAP - but this slideshow was so brilliant and easy to understand, so it is much more clear to me now, than before.
Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....
CSS Flexbox was designed to simplify creating these types of layouts.
html {
height: 100%;
}
body {
height: 100%;
display: flex;
}
.Content {
flex-grow: 1;
}
.Sidebar {
width: 290px;
flex-shrink: 0;
}
_x000D_
<div class="Content" style="background:#bed">Content</div>
<div class="Sidebar" style="background:#8cc">Sidebar</div>
_x000D_
There are tree ways methods and properties are implemented on function or class objects, and on they instances.
Foo.method()
or Foo.prop
. Those are static methods or propertiesFoo.prototype.method()
or Foo.prototype.prop
. When created, the instances will inherit those object via the prototype witch is {method:function(){...}, prop:...}
. So the foo object will receive, as prototype, a copy of the Foo.prototype object.foo={method:function(){...}, prop:...}
The this
keyword will represent and act differently according to the context. In a static method, it will represent the class itself (witch is after all an instance of Function : class Foo {}
is quite equivalent to let Foo = new Function({})
With ECMAScript 2015, that seems well implemented today, it is clearer to see the difference between class (static) methods and properties, instance methods and properties and own methods ans properties. You can thus create three method or properties having the same name, but being different because they apply to different objects, the this
keyword, in methods, will apply to, respectively, the class object itself and the instance object, by the prototype or by its own.
class Foo {
constructor(){super();}
static prop = "I am static" // see 1.
static method(str) {alert("static method"+str+" :"+this.prop)} // see 1.
prop="I am of an instance"; // see 2.
method(str) {alert("instance method"+str+" : "+this.prop)} // see 2.
}
var foo= new Foo();
foo.prop = "I am of own"; // see 3.
foo.func = function(str){alert("own method" + str + this.prop)} // see 3.
<div style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" onclick="document.getElementsByClassName('answer_list')[0].style.display = 'auto';">
this way many people detect session has expired or not. the below code may help u.
protected void Page_Init(object sender, EventArgs e)
{
if (Context.Session != null)
{
if (Session.IsNewSession)
{
HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
if (newSessionIdCookie != null)
{
string newSessionIdCookieValue = newSessionIdCookie.Value;
if (newSessionIdCookieValue != string.Empty)
{
// This means Session was timed Out and New Session was started
Response.Redirect("Login.aspx");
}
}
}
}
}
I don't like to use regex, so here is another simple solution.
public String removePunctuations(String s) {
String res = "";
for (Character c : s.toCharArray()) {
if(Character.isLetterOrDigit(c))
res += c;
}
return res;
}
Note: This will include both Letters and Digits
Try gcc -c -I/home/me/development/skia sample.c
.
String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
mediaPlayer.start()
and this play from raw folder.
int resID = myContext.getResources().getIdentifier(playSoundName,"raw",myContext.getPackageName());
MediaPlayer mediaPlayer = MediaPlayer.create(myContext,resID);
mediaPlayer.prepare();
mediaPlayer.start();
mycontext=application.this. use.
Keep the json file in Assets (parallel to app dir) directory
Note that if you would have generated with ng new YourAppname- this assets directory exists same line with 'app' directory, and services should be child directory of app directory. May look like as below:
::app/services/myservice.ts
getOrderSummary(): Observable {
// get users from api
return this.http.get('assets/ordersummary.json')//, options)
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
I think most of customtoast xml-examples throughout the Internet are based on the same source.
The Android documentation, which is very outdated in my opinion. fill_parent should not be used any more. I prefer using wrap_content in combination with a xml.9.png. That way you can define the minimum size of toastbackground throughout the size of the provided source.
If more complex toasts are required, frame or relative layout should be used instead of LL.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/points_layout"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/background"
android:layout_gravity="center"
android:gravity="center" >
<TextView
android:id="@+id/points_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:layout_margin="15dp"
android:text="@+string/points_text"
android:textColor="@color/Green" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<nine-patch
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/background_96"
android:dither="true"/>
background_96 is background_96.9.png.
This is not tested very well, and hints are appreciated :)
new String(byteArray, Charset.defaultCharset())
This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.
I have reproduced the issue in my system,
postgres=# alter user my-sys with password 'pass11';
ERROR: syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
^
Here is the issue,
psql is asking for input and you have given again the alter query see postgres-#
That's why it's giving error at alter
postgres-# alter user "my-sys" with password 'pass11';
ERROR: syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
^
Solution is as simple as the error,
postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE
If the strings you are concatenating are literals, use String literal concatenation
re.compile(
"[A-Za-z_]" # letter or underscore
"[A-Za-z0-9_]*" # letter, digit or underscore
)
This is useful if you want to comment on part of a string (as above) or if you want to use raw strings or triple quotes for part of a literal but not all.
Since this happens at the syntax layer it uses zero concatenation operators.
I did the css properties shown here as well as monitor ondragstart with the following javascript:
handleDragStart: function (evt) {
if (evt.target.nodeName.match(/^(IMG|DIV|SPAN|A)$/i)) {
evt.preventDefault();
return false;
}
},
I'd use this approach:
String randomString(final int length) {
Random r = new Random(); // perhaps make it a class variable so you don't make a new one every time
StringBuilder sb = new StringBuilder();
for(int i = 0; i < length; i++) {
char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
sb.append(c);
}
return sb.toString();
}
If you want a byte[] you can do this:
byte[] randomByteString(final int length) {
Random r = new Random();
byte[] result = new byte[length];
for(int i = 0; i < length; i++) {
result[i] = r.nextByte();
}
return result;
}
Or you could do this
byte[] randomByteString(final int length) {
Random r = new Random();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < length; i++) {
char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
sb.append(c);
}
return sb.toString().getBytes();
}
this is one:
ls -l . | egrep -c '^-'
Note:
ls -1 | wc -l
Which means:
ls
: list files in dir
-1
: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|
: pipe output onto...
wc
: "wordcount"
-l
: count l
ines.
Since the Length
property of System.String
is an Int32
, I would guess that that the maximum length would be 2,147,483,647 chars (max Int32
size). If it allowed longer you couldn't check the Length since that would fail.
This article helped explain a lot of things. It's in FAQ style.
This part explains why Thread.Sleep
runs on the same original thread - leading to my initial confusion.
Does the “async” keyword cause the invocation of a method to queue to the ThreadPool? To create a new thread? To launch a rocket ship to Mars?
No. No. And no. See the previous questions. The “async” keyword indicates to the compiler that “await” may be used inside of the method, such that the method may suspend at an await point and have its execution resumed asynchronously when the awaited instance completes. This is why the compiler issues a warning if there are no “awaits” inside of a method marked as “async”.
Is this what you are trying to do?
# Our data
text <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)
# Split into individual elements by the '.' character
# Remember to escape it, because '.' by itself matches any single character
elems <- unlist( strsplit( text , "\\." ) )
# We know the dataframe should have 4 columns, so make a matrix
m <- matrix( elems , ncol = 4 , byrow = TRUE )
# Coerce to data.frame - head() is just to illustrate the top portion
head( as.data.frame( m ) )
# V1 V2 V3 V4
#1 F US CLE V13
#2 F US CA6 U13
#3 F US CA6 U13
#4 F US CA6 U13
#5 F US CA6 U13
#6 F US CA6 U13
If you are a linux user Update node to a later version by running
sudo apt update
sudo apt install build-essential checkinstall libssl-dev
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash
nvm --version
nvm ls
nvm ls-remote
nvm install [version.number]
this should solve your problem
Ditch the <a href="...">
. Put the onclick
(all lowercase) handler on the <li>
tag itself.
The java application takes too long to respond(maybe due start-up/jvm being cold) thus you get the proxy error.
Proxy Error
The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request GET /lin/Campaignn.jsp.
As Albert Maclang said amending the http timeout configuration may fix the issue. I suspect the java application throws a 500+ error thus the apache gateway error too. You should look in the logs.
Missing prerequisites. IBM has the solution below:
yum install gtk2.i686
yum install libXtst.i686
If you received the the missing libstdc++ message above,
install the libstdc++ library:
yum install compat-libstdc++
https://www-304.ibm.com/support/docview.wss?uid=swg21459143
Using ES6 the javascript becomes a little cleaner
handleFiles(input) {
const file = input.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
const file = event.target.result;
const allLines = file.split(/\r\n|\n/);
// Reading line by line
allLines.forEach((line) => {
console.log(line);
});
};
reader.onerror = (event) => {
alert(event.target.error.name);
};
reader.readAsText(file);
}
@QueryMap
worked for me instead of FieldMap
If you have a bunch of GET params, another way to pass them into your url is a HashMap
.
class YourActivity extends Activity {
private static final String BASEPATH = "http://www.example.com";
private interface API {
@GET("/thing")
void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
API service = rest.create(API.class);
Map<String, String> params = new HashMap<String, String>();
params.put("key1", "val1");
params.put("key2", "val2");
// ... as much as you need.
service.getMyThing(params, new Callback<String>() {
// ... do some stuff here.
});
}
}
The URL called will be http://www.example.com/thing/?key1=val1&key2=val2
Note:- below is the illustration of map and flatmap function, otherwise Optional is primarily designed to be used as a return type only.
As you already may know Optional is a kind of container which may or may not contain a single object, so it can be used wherever you anticipate a null value(You may never see NPE if use Optional properly). For example if you have a method which expects a person object which may be nullable you may want to write the method something like this:
void doSome(Optional<Person> person){
/*and here you want to retrieve some property phone out of person
you may write something like this:
*/
Optional<String> phone = person.map((p)->p.getPhone());
phone.ifPresent((ph)->dial(ph));
}
class Person{
private String phone;
//setter, getters
}
Here you have returned a String type which is automatically wrapped in an Optional type.
If person class looked like this, i.e. phone is also Optional
class Person{
private Optional<String> phone;
//setter,getter
}
In this case invoking map function will wrap the returned value in Optional and yield something like:
Optional<Optional<String>>
//And you may want Optional<String> instead, here comes flatMap
void doSome(Optional<Person> person){
Optional<String> phone = person.flatMap((p)->p.getPhone());
phone.ifPresent((ph)->dial(ph));
}
PS; Never call get method (if you need to) on an Optional without checking it with isPresent() unless you can't live without NullPointerExceptions.
Just to show java 8's stance to remove null values.
String s = Optional.ofNullable(myString).orElse("");
if (s.trim().isEmpty()) {
...
}
Makes sense if you can use Optional<String>
.
You need to add type assertion .(string)
. It is necessary because the map is of type map[string]interface{}
:
host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)
Latest version of Docopt returns Opts object that has methods for conversion:
host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port
Use -Xms and -Xmx command line options when runing java:
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
For more help type java -X
in command line.
Also you can check using Keras backend function:
from keras import backend as K
K.tensorflow_backend._get_available_gpus()
I test this on Keras (2.1.1)
follow this tutorial. i ran the install-opencv.sh file in bash. its in the tutorial
read the example from openCV
CMakeLists.txt
cmake_minimum_required(VERSION 3.7)
project(openCVTest)
# cmake needs this line
cmake_minimum_required(VERSION 2.8)
# Define project name
project(opencv_example_project)
# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
find_package(OpenCV REQUIRED)
# If the package has been found, several variables will
# be set, you can find the full list with descriptions
# in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS " version: ${OpenCV_VERSION}")
message(STATUS " libraries: ${OpenCV_LIBS}")
message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")
if(CMAKE_VERSION VERSION_LESS "2.8.11")
# Add OpenCV headers location to your include paths
include_directories(${OpenCV_INCLUDE_DIRS})
endif()
# Declare the executable target built from your sources
add_executable(main main.cpp)
# Link your application with OpenCV libraries
target_link_libraries(main ${OpenCV_LIBS})
main.cpp
/**
* @file LinearBlend.cpp
* @brief Simple linear blender ( dst = alpha*src1 + beta*src2 )
* @author OpenCV team
*/
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>
using namespace cv;
/** Global Variables */
const int alpha_slider_max = 100;
int alpha_slider;
double alpha;
double beta;
/** Matrices to store images */
Mat src1;
Mat src2;
Mat dst;
//![on_trackbar]
/**
* @function on_trackbar
* @brief Callback for trackbar
*/
static void on_trackbar( int, void* )
{
alpha = (double) alpha_slider/alpha_slider_max ;
beta = ( 1.0 - alpha );
addWeighted( src1, alpha, src2, beta, 0.0, dst);
imshow( "Linear Blend", dst );
}
//![on_trackbar]
/**
* @function main
* @brief Main function
*/
int main( void )
{
//![load]
/// Read images ( both have to be of the same size and type )
src1 = imread("../data/LinuxLogo.jpg");
src2 = imread("../data/WindowsLogo.jpg");
//![load]
if( src1.empty() ) { printf("Error loading src1 \n"); return -1; }
if( src2.empty() ) { printf("Error loading src2 \n"); return -1; }
/// Initialize values
alpha_slider = 0;
//![window]
namedWindow("Linear Blend", WINDOW_AUTOSIZE); // Create Window
//![window]
//![create_trackbar]
char TrackbarName[50];
sprintf( TrackbarName, "Alpha x %d", alpha_slider_max );
createTrackbar( TrackbarName, "Linear Blend", &alpha_slider, alpha_slider_max, on_trackbar );
//![create_trackbar]
/// Show some stuff
on_trackbar( alpha_slider, 0 );
/// Wait until user press some key
waitKey(0);
return 0;
}
Tested in linux mint 17
Apart from the difference that Scripting language is Interpreted and Programming language is Compiled, there is another difference as below, which I guess has been missed..
A scripting language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. In such systems, useful functionality is already available through a user interface, and the scripting language is a mechanism for exposing that functionality to program control.
Whereas a Programming Language generally is used to code the system from Scratch.
src ECMA
Delete the following information related to signing certificate in the certificate store
<PropertyGroup>
<ManifestCertificateThumbprint>xxxxx xxxxxx</ManifestCertificateThumbprint>
<ManifestKeyFile>xxxxxxxx.pfx</ManifestKeyFile>
<GenerateManifests>true</GenerateManifests>
<SignManifests>false</SignManifests>
</PropertyGroup>
I'm outdated I know.. But a little workaround would be to put your checkbox inside a label tag, then style the label with a border:
<label class='hasborder'><input type='checkbox' /></label>
then style the label:
.hasborder { border:1px solid #F00; }
From Eugene Tskhovrebov
List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))
This solution seems to be the best for me.
Click "Tab Moves Focus" at the bottom right in the status bar.
I believe I had clicked on ctrl+M. When doing this, the "Tab Moves Focus" tab/button showed up at the bottom right. Clicking on that makes it go away and starts working again.
Hashtable<String, Object>
It is better than java.util.Properties
which is by fact an extension of Hashtable<Object, Object>
.
mysqldump doesn't work with: >nul 2>&1
Instead use: 2> nul
This suppress the stderr message: "Warning: Using a password on the command line interface can be insecure"
If you want a good format the next statement is the best:
dataframe_prediction.to_csv('filename.csv', sep=',', encoding='utf-8', index=False)
In this case you have got a csv file with ',' as separate between columns and utf-8 format. In addition, numerical index won't appear.
Just go on that directory of your JS file from cmd
and write node jsFile.js
or even node jsFile
; both will work fine.
By default Rails assumes that you have your files precompiled in the production environment, if you want use live compiling (compile your assets during runtime) in production you must set the config.assets.compile to true.
# config/environments/production.rb
...
config.assets.compile = true
...
You can use this option to fallback to Sprockets when you are using precompiled assets but there are any missing precompiled files.
If config.assets.compile
option is set to false and there are missing precompiled files you will get an "AssetNoPrecompiledError" indicating the name of the missing file.
I had a problem like this whereby I had specified the width of my Window, but had the height set to Auto
. The child DockPanel
had it's VerticalAlignment
set to Top and the Window had it's VerticalContentAlignment set to Top, yet the Window would still be much taller than the contents.
Using Snoop, I discovered that the ContentPresenter
within the Window (part of the Window, not something I had put there) has it's VerticalAlignment
set to Stretch
and can't be changed without retemplating the entire Window!
After a lot of frustration, I discovered the SizeToContent
property - you can use this to specify whether you want the Window to size vertically, horizontally or both, according to the size of the contents - everything is sizing nicely now, I just can't believe it took me so long to find that property!
If you want to run your scripts, then
mysql -u root -p < yourscript.sql
Functions mysql_
are not supported any longer and have been removed in PHP 7
. You must use mysqli_
instead. However it's not recommended method now. You should consider PDO
with better security solutions.
$result = mysqli_query($con, "SELECT option_value FROM wp_10_options WHERE option_name='homepage' LIMIT 1");
$row = mysqli_fetch_assoc($result);
echo $row['option_value'];
Calling preventDefault
on touchmove
while you're actively scrolling is not working in Chrome. To prevent performance issues, you cannot interrupt a scroll.
Try to call preventDefault()
from touchstart
and everything should be ok.
char arr[3] = "bo";
The arr takes the memory into the stack segment. which will be automatically free, if arr goes out of scope.
Sometimes you have to use @import as opposed to inline . If you are working on a complex application that has 32 or more css files and you must support IE9 there is no choice. IE9 ignores any css file after the first 31 and this includes and inline css. However, each sheet can import 31 others.
Try using a style and set colorControlActivated too desired ProgressBar color.
<style name="progressColor" parent="Widget.AppCompat.ProgressBar">
<item name="colorControlActivated">@color/COLOR</item>
</style>
Then set the theme of the ProgressBar to new style.
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/progressColor"
/>
I simply had to add -h localhost
If you need SHA1 for Google Maps, you can just see your error log in LogCat.
The mySQL client by default attempts to connect through a local file called a socket instead of connecting to the loopback address (127.0.0.1) for localhost.
The default location of this socket file, at least on OSX, is /tmp/mysql.sock
.
QUICK, LESS ELEGANT SOLUTION
Create a symlink to fool the OS into finding the correct socket.
ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp
PROPER SOLUTION
Change the socket path defined in the startMysql.sh
file in /Applications/MAMP/bin
.
To complicate matters further, there is such a thing as thread-local storage, and Unix shared memory.
Thread-local storage allows each thread to have a separate instance of global objects. The only time I've used it was when constructing an emulation environment on linux/windows, for application code that ran in an RTOS. In the RTOS each task was a process with it's own address space, in the emulation environment, each task was a thread (with a shared address space). By using TLS for things like singletons, we were able to have a separate instance for each thread, just like under the 'real' RTOS environment.
Shared memory can (obviously) give you the performance benefits of having multiple processes access the same memory, but at the cost/risk of having to synchronize the processes properly. One way to do that is have one process create a data structure in shared memory, and then send a handle to that structure via traditional inter-process communication (like a named pipe).
Here is a working plunkr with a filter and sortBy pipe. https://plnkr.co/edit/vRvnNUULmBpkbLUYk4uw?p=preview
As developer033 mentioned in a comment, you are passing in a single value to the filter pipe, when the filter pipe is expecting an array of values. I would tell the pipe to expect a single value instead of an array
export class FilterPipe implements PipeTransform {
transform(items: any[], term: string): any {
// I am unsure what id is here. did you mean title?
return items.filter(item => item.id.indexOf(term) !== -1);
}
}
I would agree with DeborahK that impure pipes should be avoided for performance reasons. The plunkr includes console logs where you can see how much the impure pipe is called.
the pro's to using system("PAUSE"); while creating the small portions of your program is for debugging it yourself. if you use it to get results of variables before during and after each process you are using to assure that they are working properly.
After testing and moving it into full swing with the rest of the solution you should remove these lines. it is really good when testing an user-defined algorithm and assuring that you are doing things in the proper order for results that you want.
In no means do you want to use this in an application after you have tested it and assured that it is working properly. However it does allow you to keep track of everything that is going on as it happens. Don't use it for End-User apps at all.
For OS X you can use Charles, it's simple and easy to use.
For more information, please have a look at Android Emulator and Charles Proxy blog post.
I am posting a way to use _netrc
to download materials from the site www.course.com.
If someone is going to use the coursera-dl to download the open-class materials on www.coursera.com, and on the Windows OS someone wants to use a file like ".netrc" which is in like-Unix OS to add the option -n
instead of -U <username> -P <password>
for convenience. He/she can do it like this:
Check the home path on Windows OS: setx HOME %USERPROFILE%
(refer to VonC's answer). It will save the HOME
environment variable as C:\Users\"username"
.
Locate into the directory C:\Users\"username"
and create a file name _netrc
.NOTE: there is NOT any suffix.
the content is like: machine coursera-dl login <user> password <pass>
Use a command like coursera-dl -n --path PATH <course name>
to download the class materials. More coursera-dl options details for this page.
Let the number be n
then the number of digits in n
is given by:
math.floor(math.log10(n))+1
Note that this will give correct answers for +ve integers < 10e15. Beyond that the precision limits of the return type of math.log10
kicks in and the answer may be off by 1. I would simply use len(str(n))
beyond that; this requires O(log(n))
time which is same as iterating over powers of 10.
Thanks to @SetiVolkylany for bringing my attenstion to this limitation. Its amazing how seemingly correct solutions have caveats in implementation details.
Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n
and you use \n
.
I know this is an old question but it's worth noting that BlackBerry doesn't support overflow-x
or overflow-y
.
See my post here
select top 10 p.id from(select distinct p.id from tablename)tablename
Just tested it myself and here's how I approached it. Pretty straight forward, let me know if you need any clarification
HTML
<div id="map_canvas" style="width:700px; height:500px; margin-left:80px;" ></div>
<button onclick="displayMap()">Show Map</button>
CSS
<style type="text/css">
#map_canvas {display:none;}
</style>
Javascript
<script>
function displayMap()
{
document.getElementById( 'map_canvas' ).style.display = "block";
initialize();
}
function initialize()
{
// create the map
var myOptions = {
zoom: 14,
center: new google.maps.LatLng( 0.0, 0.0 ),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map( document.getElementById( "map_canvas" ),myOptions );
}
</script>
The link you gave does actually describe the differences, but it's buried at the bottom of the page:
http://www.cplusplus.com/reference/cstdio/fopen/
Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.
The conversion could be to normalize \r\n
to \n
(or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.
SELECT SUM(Output.count),Output.attr
FROM
(
SELECT COUNT(column1 ) AS count,column1 AS attr FROM tab1 GROUP BY column1
UNION ALL
SELECT COUNT(column2) AS count,column2 AS attr FROM tab1 GROUP BY column2
UNION ALL
SELECT COUNT(column3) AS count,column3 AS attr FROM tab1 GROUP BY column3) AS Output
GROUP BY attr
In 7.3 just enable Properties/Build/Package/Copy Dependent Libraries and main class will be added to manifest when building depending on selected target.
I personally don't like a comment "toggle" function, as it will destroy comments wich are already included in the code. Also, I want to have the comment char appear on the far left, always, so I can easily see comment blocks. Also I want this to work nested (if I first comment out a block and later an enclosing block). Therefore, I slightly changed one of the solutions. I use F5 to comment and Shift-F5 to uncomment. Also, I added a /g at the end of the s/ command:
autocmd FileType c,cpp,java,scala let b:comment_leader = '//'
autocmd FileType sh,ruby,python let b:comment_leader = '#'
autocmd FileType conf,fstab let b:comment_leader = '#'
autocmd FileType tex let b:comment_leader = '%'
autocmd FileType mail let b:comment_leader = '>'
autocmd FileType vim let b:comment_leader = '"'
autocmd FileType nasm let b:comment_leader = ';'
function! CommentLine()
execute ':silent! s/^\(.*\)/' . b:comment_leader . ' \1/g'
endfunction
function! UncommentLine()
execute ':silent! s/^' . b:comment_leader . ' //g'
endfunction
map <F5> :call CommentLine()<CR>
map <S-F5> :call UncommentLine()<CR>
You have to change the values in the CATALINA_OPTS option defined in the Tomcat Catalina start file. To increase the PermGen
memory change the value of the MaxPermSize
variable, otherwise change the value of the Xmx
variable.
Linux & Mac OS: Open or create setenv.sh
file placed in the "bin" directory. You have to apply the changes to this line:
export CATALINA_OPTS="$CATALINA_OPTS -server -Xms256m -Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m"
Windows:
Open or create the setenv.bat
file placed in the "bin" directory:
set CATALINA_OPTS=-server -Xms256m -Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m
I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.
_kbhit()
and _getwch()
from msvcrt.dll.tcsetattr()
to switch the console to non-canonical mode, System.in.available()
to check whether data is available and System.in.read()
to read bytes from the console. A CharsetDecoder
is used to convert bytes to characters.It supports non-blocking input and mixing raw mode and normal line mode input.
In SSMS expand your database in Object Explorer, go to Tables, right click on the table you're interested in and select Script Table As, Create To, New Query Editor Window.
Do a find and replace (CTRL + H) to change the table name (i.e. put ABC
in the Find What field and ABC_1
in the Replace With then click OK).
The other answers showing how to do this by SQL also work well, but the difference with this method is you'll also get any indexes, constraints and triggers.
If you want to include data, after creating this table run the below script to copy all data from ABC (keeping the same ID values if you have an identity field):
set identity_insert ABC_1 on
insert into ABC_1 (column1, column2) select column1, column2 from ABC
set identity_insert ABC_1 off
It is worth noting that you can build upon Gavin Toweys answer by using multiple fields from across your query such as
SUM(table.field = 1 AND table2.field = 2)
You can also use this syntax for COUNT
and I am sure other functions as well.
The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/
Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)
See this question for additional information.
As @kgr mentioned, MySQL 8.0.11 made some changes to the authentication method.
I've opened a phpMyAdmin bug report about this: https://github.com/phpmyadmin/phpmyadmin/issues/14220.
MySQL 8.0.4-rc was working fine for me, and I kind of think it's ridiculous for MySQL to make such a change in a patch level release.
Yes: TIME_CREATED contains a date and a time. Use TRUNC
to strip the time:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy')
UPDATE:
As Dave Costa points out in the comment below, this will prevent Oracle from using the index of the column TIME_CREATED
if it exists. An alternative approach without this problem is this:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED >= TO_DATE('26/JAN/2011','dd/mon/yyyy')
AND TIME_CREATED < TO_DATE('26/JAN/2011','dd/mon/yyyy') + 1
Date:2017-12-04
Every possible solution has been listed in other answers.
An intuitive and arguable way to check if a file exists is the following:
import os
os.path.isfile('~/file.md') # Returns True if exists, else False
# additionaly check a dir
os.path.isdir('~/folder') # Returns True if the folder exists, else False
# check either a dir or a file
os.path.exists('~/file')
I made an exhaustive cheatsheet for your reference:
#os.path methods in exhaustive cheatsheet
{'definition': ['dirname',
'basename',
'abspath',
'relpath',
'commonpath',
'normpath',
'realpath'],
'operation': ['split', 'splitdrive', 'splitext',
'join', 'normcase'],
'compare': ['samefile', 'sameopenfile', 'samestat'],
'condition': ['isdir',
'isfile',
'exists',
'lexists'
'islink',
'isabs',
'ismount',],
'expand': ['expanduser',
'expandvars'],
'stat': ['getatime', 'getctime', 'getmtime',
'getsize']}
Just for the record, I tried translating Dirk's answer into code :-P
temp <- tempfile()
download.file("http://www.newcl.org/data/zipfiles/a1.zip",temp)
con <- unz(temp, "a1.dat")
data <- matrix(scan(con),ncol=4,byrow=TRUE)
unlink(temp)
Don't make data frames. Keep the list, name its elements but do not attach it.
The biggest reason for this is that if you make variables on the go, almost always you will later on have to iterate through each one of them to perform something useful. There you will again be forced to iterate through each one of the names that you have created on the fly.
It is far easier to name the elements of the list and iterate through the names.
As far as attach is concerned, its really bad programming practice in R and can lead to a lot of trouble if you are not careful.
I don't think such a thing is possible. You can use SUBSTRING
function to extract the part you want.
Short answer: You can't.
CSS does not have techniques which affect the rendering of fonts in the browser; only the system can do that.
Obviously, text sharpness can easily be achieved with pixel-dense screens, but if you're using a normal PC that's gonna be hard to achieve.
There are some newer fonts that are smooth but at the sacrifice of it appearing somewhat blurry (look at most of Adobe's fonts, for example). You can also find some smooth-but-blurry-by-design fonts at Google Fonts, however.
There are some new CSS3 techniques for font rendering and text effects though the consistency, performance, and reliability of these techniques vary so largely to the point where you generally shouldn't rely on them too much.
Any() returns true if any of the elements in a collection meet your predicate's criteria.
Where() returns an enumerable of all elements in a collection that meet your predicate's criteria.
Exists() does the same thing as any except it's just an older implementation that was there on the IList back before Linq.
this worked for me:
var blobToBase64 = function(blob, callback) {
var reader = new FileReader();
reader.onload = function() {
var dataUrl = reader.result;
var base64 = dataUrl.split(',')[1];
callback(base64);
};
reader.readAsDataURL(blob);
};
You should also use the style 'color' and not 'font-color'
<?php
foreach($months as $key => $month){
if(strpos($filename,$month)!==false){
echo "<style = 'color: #ff0000;'> Movie List for {$key} 2013 </style>";
}
}
?>
In general, the comments on double and single quotes are correct in other suggestions. $Variables only execute in double quotes.
Here's some more detailed information on what Client, Resource, and Session are all about.
Client:
Here's an example of client-level access to an S3 bucket's objects (at most 1000**):
import boto3
client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
print(content['Key'], obj_dict['LastModified'])
** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.
Resource:
Here's the equivalent example using resource-level access to an S3 bucket's objects (all):
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
print(obj.key, obj.last_modified)
Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.
You can see that the Resource
version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client
version of the code would actually be more complicated than shown above if you wanted to include pagination.
Session:
A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.
For a API v3 solution, refer to:
http://blog.enbake.com/draw-circle-with-google-maps-api-v3
It creates circle around points and then show markers within and out of the range with different colors. They also calculate dynamic radius but in your case radius is fixed so may be less work.
For Those looking in 2020. The following is for Windows 10 Machine:
The other answers so far have a lot of technical information. I will try to answer, as requested, in simple terms.
Serialization is what you do to an instance of an object if you want to dump it to a raw buffer, save it to disk, transport it in a binary stream (e.g., sending an object over a network socket), or otherwise create a serialized binary representation of an object. (For more info on serialization see Java Serialization on Wikipedia).
If you have no intention of serializing your class, you can add the annotation just above your class @SuppressWarnings("serial")
.
If you are going to serialize, then you have a host of things to worry about all centered around the proper use of UUID. Basically, the UUID is a way to "version" an object you would serialize so that whatever process is de-serializing knows that it's de-serializing properly. I would look at Ensure proper version control for serialized objects for more information.
The one way is by using webservice, simply write a webservice method in PHP or any other language . And From your android app by using http client request and response , you can hit the web service method which will return whatever you want.
For PHP You can create a webservice like this. Assuming below we have a php file in the server. And the route of the file is yourdomain.com/api.php
if(isset($_GET['api_call'])){
switch($_GET['api_call']){
case 'userlogin':
//perform your userlogin task here
break;
}
}
Now you can use Volley or Retrofit to send a network request to the above PHP Script and then, actually the php script will handle the database operation.
In this case the PHP script is called a RESTful API.
You can learn all the operation at MySQL from this tutorial. Android MySQL Tutorial to Perform CRUD.
Do you want to match a class exactly, e.g. only matching FileInputStream
instead of any subclass of FileInputStream
? If so, use getClass()
and ==
. I would typically do this in an equals
, so that an instance of X isn't deemed equal to an instance of a subclass of X - otherwise you can get into tricky symmetry problems. On the other hand, that's more usually useful for comparing that two objects are of the same class than of one specific class.
Otherwise, use instanceof
. Note that with getClass()
you will need to ensure you have a non-null reference to start with, or you'll get a NullPointerException
, whereas instanceof
will just return false
if the first operand is null.
Personally I'd say instanceof
is more idiomatic - but using either of them extensively is a design smell in most cases.
Pass param rot=0
to rotate the xticks:
import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
df = df[["celltype","s1","s2"]]
df.set_index(["celltype"],inplace=True)
df.plot(kind='bar',alpha=0.75, rot=0)
plt.xlabel("")
plt.show()
yields plot:
If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:
Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.
Basically, you can do something like this:
function doCall(urlToCall) {
return co(function *(){
var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return finalData;
});
}
Then,
var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.
By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.
The way this effect works is very simple. The element is given a background which is the gradient. It goes from one color to another depending on the colors and color-stop percentages given for it.
For example, in rainbow text sample (note that I've converted the gradient into the standard syntax):
#f22
at 0%
(that is the left edge of the element). First color is always assumed to start at 0%
even though the percentage is not mentioned explicitly.0%
to 14.25%
, the color changes from #f22
to #f2f
gradually. The percenatge is set at 14.25
because there are seven color changes and we are looking for equal splits.14.25%
(of the container's size), the color will exactly be #f2f
as per the gradient specified.14.25%
.So, we end up getting a gradient like in the below snippet. Now this alone would mean the background applies to the entire element and not just the text.
.rainbow {_x000D_
background-image: linear-gradient(to right, #f22, #f2f 14.25%, #22f 28.5%, #2ff 42.75%, #2f2 57%, #2f2 71.25%, #ff2 85.5%, #f22);_x000D_
color: transparent;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>
_x000D_
Since, the gradient needs to be applied only to the text and not to the element on the whole, we need to instruct the browser to clip the background from the areas outside the text. This is done by setting background-clip: text
.
(Note that the background-clip: text
is an experimental property and is not supported widely.)
Now if you want the text to have a simple 3 color gradient (that is, say from red - orange - brown), we just need to change the linear-gradient specification as follows:
to right
. If it should be red at right and brown at left then give the direction as to left
.red
as the first color (percentage is assumed to be 0%).50%
the color should be orange
and then the final color would be brown
. The position of the final color is always assumed to be at 100%.Thus the gradient's specification should read as follows:
background-image: linear-gradient(to right, red, orange 50%, brown).
If we form the gradients using the above mentioned method and apply them to the element, we can get the required effect.
.red-orange-brown {_x000D_
background-image: linear-gradient(to right, red, orange 50%, brown);_x000D_
color: transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}_x000D_
.green-yellowgreen-yellow-gold {_x000D_
background-image: linear-gradient(to right, green, yellowgreen 33%, yellow 66%, gold);_x000D_
color: transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}
_x000D_
<span class="red-orange-brown">Red to Orange to Brown</span>_x000D_
_x000D_
<br>_x000D_
_x000D_
<span class="green-yellowgreen-yellow-gold">Green to Yellow-green to Yellow to Gold</span>
_x000D_
Take a look at the write.csv
or the write.table
functions. You just have to supply the file name the user selects to the file
parameter, and the dataframe to the x
parameter:
write.csv(x=df, file="myFileName")
On the CREATE TABLE,
The AUTO_INCREMENT of abuse_id is set to 2. MySQL now thinks 1 already exists.
With the INSERT statement you are trying to insert abuse_id with record 1. Please set AUTO_INCREMENT on CREATE_TABLE to 1 and try again.
Otherwise set the abuse_id in the INSERT statement to 'NULL'.
How can i resolve this?
My 2 cents, from a current implementation Point of View and for SWIG users on k8 (x86_64) architecture.
First long long
and long int
are different types
but sizeof(long long) == sizeof(long int) == sizeof(int64_t)
First try to find where and how the compiler define int64_t and uint64_t
grepc -rn "typedef.*INT64_TYPE" /lib/gcc
/lib/gcc/x86_64-linux-gnu/9/include/stdint-gcc.h:43:typedef __INT64_TYPE__ int64_t;
/lib/gcc/x86_64-linux-gnu/9/include/stdint-gcc.h:55:typedef __UINT64_TYPE__ uint64_t;
So we need to find this compiler macro definition
gcc -dM -E -x c /dev/null | grep __INT64
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int
gcc -dM -E -x c++ /dev/null | grep __INT64
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int
clang -dM -E -x c++ /dev/null | grep INT64_TYPE
#define __INT64_TYPE__ long int
#define __UINT64_TYPE__ long unsigned int
Clang, GNU compilers:
-dM
dumps a list of macros.
-E
prints results to stdout instead of a file.
-x c
and -x c++
select the programming language when using a file without a filename extension, such as /dev/null
note: for swig user, on Linux x86_64 use -DSWIGWORDSIZE64
On Catalina 10.15 IIRC
clang -dM -E -x c++ /dev/null | grep INT64_TYPE
#define __INT64_TYPE__ long long int
#define __UINT64_TYPE__ long long unsigned int
Clang:
-dM
dumps a list of macros.
-E
prints results to stdout instead of a file.
-x c
and -x c++
select the programming language when using a file without a filename extension, such as /dev/null
note: for swig user, on macOS x86_64 don't use -DSWIGWORDSIZE64
First
sizeof(long int) == 4
and sizeof(long long) == 8
in stdint.h
we have:
#if _VCRT_COMPILER_PREPROCESSOR
typedef signed char int8_t;
typedef short int16_t;
typedef int int32_t;
typedef long long int64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
note: for swig user, on windows x86_64 don't use -DSWIGWORDSIZE64
First see https://github.com/swig/swig/blob/3a329566f8ae6210a610012ecd60f6455229fe77/Lib/stdint.i#L20-L24 so you can control the typedef using SWIGWORDSIZE64
but...
now the bad: SWIG Java and SWIG CSHARP do not take it into account
So you may want to use
#if defined(SWIGJAVA)
#if defined(SWIGWORDSIZE64)
%define PRIMITIVE_TYPEMAP(NEW_TYPE, TYPE)
%clear NEW_TYPE;
%clear NEW_TYPE *;
%clear NEW_TYPE &;
%clear const NEW_TYPE &;
%apply TYPE { NEW_TYPE };
%apply TYPE * { NEW_TYPE * };
%apply TYPE & { NEW_TYPE & };
%apply const TYPE & { const NEW_TYPE & };
%enddef // PRIMITIVE_TYPEMAP
PRIMITIVE_TYPEMAP(long int, long long);
PRIMITIVE_TYPEMAP(unsigned long int, long long);
#undef PRIMITIVE_TYPEMAP
#endif // defined(SWIGWORDSIZE64)
#endif // defined(SWIGJAVA)
and
#if defined(SWIGCSHARP)
#if defined(SWIGWORDSIZE64)
%define PRIMITIVE_TYPEMAP(NEW_TYPE, TYPE)
%clear NEW_TYPE;
%clear NEW_TYPE *;
%clear NEW_TYPE &;
%clear const NEW_TYPE &;
%apply TYPE { NEW_TYPE };
%apply TYPE * { NEW_TYPE * };
%apply TYPE & { NEW_TYPE & };
%apply const TYPE & { const NEW_TYPE & };
%enddef // PRIMITIVE_TYPEMAP
PRIMITIVE_TYPEMAP(long int, long long);
PRIMITIVE_TYPEMAP(unsigned long int, unsigned long long);
#undef PRIMITIVE_TYPEMAP
#endif // defined(SWIGWORDSIZE64)
#endif // defined(SWIGCSHARP)
So int64_t
aka long int
will be bind to Java/C# long
on Linux...
func paramsFromJSON(json: String) -> [String : AnyObject]?
{
let objectData: NSData = (json.dataUsingEncoding(NSUTF8StringEncoding))!
var jsonDict: [ String : AnyObject]!
do {
jsonDict = try NSJSONSerialization.JSONObjectWithData(objectData, options: .MutableContainers) as! [ String : AnyObject]
return jsonDict
} catch {
print("JSON serialization failed: \(error)")
return nil
}
}
let json = Mapper().toJSONString(loginJSON, prettyPrint: false)
Alamofire.request(.POST, url + "/login", parameters: paramsFromJSON(json!), encoding: .JSON)
The string has a substring method that returns the string at the specified position.
String name="123456789";
System.out.println(name.substring(0,1));
It's entirely possible if your code has enough relative logic to work with.
Simply use the viewport units though for some the math may be a bit more complicated. I used this to prevent list items from bloating certain table columns with much longer text.
ol {max-width: 10vw; padding: 0; overflow: hidden;}
Apparently max-width
on colgroup
elements do not work which is pretty lame to be dependent entirely on child elements to control something on the parent.
You can use git add -i
to get an interactive version of git add
, although that's not exactly what you're after. The simplest thing to do is, after having git add
ed, use git status
to see what is staged or not.
Using git add .
isn't really recommended unless it's your first commit. It's usually better to explicitly list the files you want staged, so that you don't start tracking unwanted files accidentally (temp files and such).
Here is an example of how to generate classes from wsdl with jaxws maven plugin from a url or from a file location (from wsdl file location is commented).
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<build>
<plugins>
<!-- usage of jax-ws maven plugin-->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>1.12</version>
<executions>
<execution>
<id>wsimport-from-jdk</id>
<goals>
<goal>wsimport</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- using wsdl from an url -->
<wsdlUrls>
<wsdlUrl>
http://myWSDLurl?wsdl
</wsdlUrl>
</wsdlUrls>
<!-- or using wsdls file directory -->
<!-- <wsdlDirectory>src/wsdl</wsdlDirectory> -->
<!-- which wsdl file -->
<!-- <wsdlFiles> -->
<!-- <wsdlFile>myWSDL.wsdl</wsdlFile> -->
<!--</wsdlFiles> -->
<!-- Keep generated files -->
<keep>true</keep>
<!-- Package name -->
<packageName>com.organization.name</packageName>
<!-- generated source files destination-->
<sourceDestDir>target/generatedclasses</sourceDestDir>
</configuration>
</plugin>
</plugins>
</build>
#pragma pack
instructs the compiler to pack structure members with particular alignment. Most compilers, when you declare a struct, will insert padding between members to ensure that they are aligned to appropriate addresses in memory (usually a multiple of the type's size). This avoids the performance penalty (or outright error) on some architectures associated with accessing variables that are not aligned properly. For example, given 4-byte integers and the following struct:
struct Test
{
char AA;
int BB;
char CC;
};
The compiler could choose to lay the struct out in memory like this:
| 1 | 2 | 3 | 4 |
| AA(1) | pad.................. |
| BB(1) | BB(2) | BB(3) | BB(4) |
| CC(1) | pad.................. |
and sizeof(Test)
would be 4 × 3 = 12, even though it only contains 6 bytes of data. The most common use case for the #pragma
(to my knowledge) is when working with hardware devices where you need to ensure that the compiler does not insert padding into the data and each member follows the previous one. With #pragma pack(1)
, the struct above would be laid out like this:
| 1 |
| AA(1) |
| BB(1) |
| BB(2) |
| BB(3) |
| BB(4) |
| CC(1) |
And sizeof(Test)
would be 1 × 6 = 6.
With #pragma pack(2)
, the struct above would be laid out like this:
| 1 | 2 |
| AA(1) | pad.. |
| BB(1) | BB(2) |
| BB(3) | BB(4) |
| CC(1) | pad.. |
And sizeof(Test)
would be 2 × 4 = 8.
Order of variables in struct is also important. With variables ordered like following:
struct Test
{
char AA;
char CC;
int BB;
};
and with #pragma pack(2)
, the struct would be laid out like this:
| 1 | 2 |
| AA(1) | CC(1) |
| BB(1) | BB(2) |
| BB(3) | BB(4) |
and sizeOf(Test)
would be 3 × 2 = 6.
The new cv2
interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:
import cv2 # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)
This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:
blank_image[:,0:width//2] = (255,0,0) # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)
If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2
interface rather than the older cv
one. I made the change recently and have never looked back. You can read more about cv2
at the OpenCV Change Logs.
Offset Means "the amount or distance by which something is out of line". Margin or Borders are something which makes the actual height or width of an HTML element "out of line". It will help you to remember that :
- offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.
On the other hand, clientHeight is something which is you can say kind of the opposite of OffsetHeight. It doesn't include the border or margins. It does include the padding because it is something that resides inside of the HTML container, so it doesn't count as extra measurements like margin or border. So :
- clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.
ScrollHeight is all the scrollable area, so your scroll will never run over your margin or border, so that's why scrollHeight doesn't include margin or borders but yeah padding does. So:
- scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.
Like others have said, you need to provide the UniqueID of the control to the __doPostback() method.
__doPostBack('<%= btn.UniqueID %>', '');
On the server, the submitted form values are identified by the name attribute of the fields in the page.
The reason why UniqueID works is because UniqueID and name are in fact the same thing when the server control is rendered in HTML.
Here's an article that describes what is the UniqueID:
The UniqueID property is also used to provide value for the HTML "name" attribute of input fields (checkboxes, dropdown lists, and hidden fields). UniqueID also plays major role in postbacks. The UniqueID property of a server control, which supports postbacks, provides data for the __EVENTTARGET hidden field. The ASP.NET Runtime then uses the __EVENTTARGET field to find the control which triggered the postback and then calls its RaisePostBackEvent method.
src: https://www.telerik.com/blogs/the-difference-between-id-clientid-and-uniqueid
The easiest way is:
s = '"sajdkasjdsaasdasdasds"'
import json
s = json.loads(s)
4 decimal places would give you the accuracy to store the world's smallest currency sub-units. You can take it down further if you need micropayment (nanopayment?!) accuracy.
I too prefer DECIMAL
to DBMS-specific money types, you're safer keeping that kind of logic in the application IMO. Another approach along the same lines is simply to use a [long] integer, with formatting into ¤unit.subunit for human readability (¤ = currency symbol) done at the application level.
You can use the replace
function
UPDATE your_table SET field = REPLACE(your_field, 'cat','dog')
The function definition is as follows (got from here):
replace(string text, from text, to text)
and returns the modified text. You can also check out this sql fiddle.
Hello Googlers from the future.
On MacOS >= High Sierra, the SSH key is no longer saved to the KeyChain because of reasons.
Using ssh-add -K
no longer survives restarts as well.
Here are 3 possible solutions.
I've used the first method successfully. I've created a file called config
in ~/.ssh
:
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa
very basic:
<?php
$username = 'user';
$password = 'password';
$server = 'localhost';
// Opens a connection to a MySQL server
$connection = mysql_connect ($server, $username, $password) or die('try again in some minutes, please');
//if you want to suppress the error message, substitute the connection line for:
//$connection = @mysql_connect($server, $username, $password) or die('try again in some minutes, please');
?>
result:
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost' (using password: YES) in /home/user/public_html/zdel1.php on line 6 try again in some minutes, please
as per Wrikken's recommendation below, check out a complete error handler for more complex, efficient and elegant solutions: http://www.php.net/manual/en/function.set-error-handler.php
Well, as far as primitive integer types go, Java doesnt handle Over/Underflow at all (for float and double the behaviour is different, it will flush to +/- infinity just as IEEE-754 mandates).
When adding two int's, you will get no indication when an overflow occurs. A simple method to check for overflow is to use the next bigger type to actually perform the operation and check if the result is still in range for the source type:
public int addWithOverflowCheck(int a, int b) {
// the cast of a is required, to make the + work with long precision,
// if we just added (a + b) the addition would use int precision and
// the result would be cast to long afterwards!
long result = ((long) a) + b;
if (result > Integer.MAX_VALUE) {
throw new RuntimeException("Overflow occured");
} else if (result < Integer.MIN_VALUE) {
throw new RuntimeException("Underflow occured");
}
// at this point we can safely cast back to int, we checked before
// that the value will be withing int's limits
return (int) result;
}
What you would do in place of the throw clauses, depends on your applications requirements (throw, flush to min/max or just log whatever). If you want to detect overflow on long operations, you're out of luck with primitives, use BigInteger instead.
Edit (2014-05-21): Since this question seems to be referred to quite frequently and I had to solve the same problem myself, its quite easy to evaluate the overflow condition by the same method a CPU would calculate its V flag.
Its basically a boolean expression that involves the sign of both operands as well as the result:
/**
* Add two int's with overflow detection (r = s + d)
*/
public static int add(final int s, final int d) throws ArithmeticException {
int r = s + d;
if (((s & d & ~r) | (~s & ~d & r)) < 0)
throw new ArithmeticException("int overflow add(" + s + ", " + d + ")");
return r;
}
In java its simpler to apply the expression (in the if) to the entire 32 bits, and check the result using < 0 (this will effectively test the sign bit). The principle works exactly the same for all integer primitive types, changing all declarations in above method to long makes it work for long.
For smaller types, due to the implicit conversion to int (see the JLS for bitwise operations for details), instead of checking < 0, the check needs to mask the sign bit explicitly (0x8000 for short operands, 0x80 for byte operands, adjust casts and parameter declaration appropiately):
/**
* Subtract two short's with overflow detection (r = d - s)
*/
public static short sub(final short d, final short s) throws ArithmeticException {
int r = d - s;
if ((((~s & d & ~r) | (s & ~d & r)) & 0x8000) != 0)
throw new ArithmeticException("short overflow sub(" + s + ", " + d + ")");
return (short) r;
}
(Note that above example uses the expression need for subtract overflow detection)
So how/why do these boolean expressions work? First, some logical thinking reveals that an overflow can only occur if the signs of both arguments are the same. Because, if one argument is negative and one positive, the result (of add) must be closer to zero, or in the extreme case one argument is zero, the same as the other argument. Since the arguments by themselves can't create an overflow condition, their sum can't create an overflow either.
So what happens if both arguments have the same sign? Lets take a look at the case both are positive: adding two arguments that create a sum larger than the types MAX_VALUE, will always yield a negative value, so an overflow occurs if arg1 + arg2 > MAX_VALUE. Now the maximum value that could result would be MAX_VALUE + MAX_VALUE (the extreme case both arguments are MAX_VALUE). For a byte (example) that would mean 127 + 127 = 254. Looking at the bit representations of all values that can result from adding two positive values, one finds that those that overflow (128 to 254) all have bit 7 set, while all that do not overflow (0 to 127) have bit 7 (topmost, sign) cleared. Thats exactly what the first (right) part of the expression checks:
if (((s & d & ~r) | (~s & ~d & r)) < 0)
(~s & ~d & r) becomes true, only if, both operands (s, d) are positive and the result (r) is negative (the expression works on all 32 bits, but the only bit we're interested in is the topmost (sign) bit, which is checked against by the < 0).
Now if both arguments are negative, their sum can never be closer to zero than any of the arguments, the sum must be closer to minus infinity. The most extreme value we can produce is MIN_VALUE + MIN_VALUE, which (again for byte example) shows that for any in range value (-1 to -128) the sign bit is set, while any possible overflowing value (-129 to -256) has the sign bit cleared. So the sign of the result again reveals the overflow condition. Thats what the left half (s & d & ~r) checks for the case where both arguments (s, d) are negative and a result that is positive. The logic is largely equivalent to the positive case; all bit patterns that can result from adding two negative values will have the sign bit cleared if and only if an underflow occured.
Try something like this onclick="return self.close()"
document.getElementById("img-id").src = document.getElementById("img-id").src
set its own src as its src.
I like using the following to prevent things being outside my div
elements. It helps with CSS rollovers too.
.marquee{
overflow:hidden;
}
this will hide anything that moves/is outside of the div which will prevent the browser expanding and causing a scroll bar to appear.
A simplified one I've just made, does what I need it to. Have limited it to just alphanumeric, period, underscore and @.
<input onKeyUp="testEmailChars(this);"><span id="a"></span>
function testEmailChars(el){
var email = $(el).val();
if ( /^[[email protected]]+$/.test(email)==true ){
$("#a").html("valid");
} else {
$("#a").html("not valid");
}
}
Made with help from others
Do you actually have the single quotes in your command? I don't think they are necessary. Plus, I think you also need --no-auth-cache
and --non-interactive
Here is what I use (no single quotes)
--non-interactive --no-auth-cache --username XXXX --password YYYY
See the Client Credentials Caching documentation in the svnbook for more information.
I just add three rules before spring default rule (/**) to tuckey's urlrewritefilter (urlrewrite.xml) to solve the problem
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.0//EN" "http://tuckey.org/res/dtds/urlrewrite3.0.dtd">
<urlrewrite default-match-type="wildcard">
<rule>
<from>/</from>
<to>/app/welcome</to>
</rule>
<rule>
<from>/scripts/**</from>
<to>/scripts/$1</to>
</rule>
<rule>
<from>/styles/**</from>
<to>/styles/$1</to>
</rule>
<rule>
<from>/images/**</from>
<to>/images/$1</to>
</rule>
<rule>
<from>/**</from>
<to>/app/$1</to>
</rule>
<outbound-rule>
<from>/app/**</from>
<to>/$1</to>
</outbound-rule>
</urlrewrite>
You can also use update_or_create just like get_or_create and here is the pattern I follow for update_or_create assuming a model Person with id (key), name, age, is_manager as attributes -
update_values = {"is_manager": False}
new_values = {"name": "Bob", "age": 25, "is_manager":True}
obj, created = Person.objects.update_or_create(identifier='id',
defaults=update_values)
if created:
obj.update(**new_values)
Use the str_contains
function.
if (str_contains($str, "."))
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
if (strpos($str, '.') !== FALSE)
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
Note that you need to use the !==
operator. If you use !=
or <>
and the '.'
is found at position 0
, the comparison will evaluate to true because 0
is loosely equal to false
.
A JSON document basically consists of lists and dictionaries. There is no obvious way to map such a datastructure on a two-dimensional table.
This error can be due to many many things.
The key here seems the hint about error reading
. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.
You could also try with sudo
, that might solve a permission problem if that's the case.
Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...
IE has a setting, located in Tools
/ Internet options
/ Advanced
/ Browsing
, called Reuse windows for launching shortcuts
, which is checked by default. For IE versions that support tabbed browsing, this option is relevant only when tab browsing is turned off (in fact, IE9 Beta explicitly mentions this). However, since IE6 does not have tabbed browsing, this option does affect opening URLs through the shell (as in your example).
You can put an apostrophe in a single quoted JavaScript string by escaping it with a backslash, like so:
theAnchorText = 'I\'m home';
Inside your component class:
checkValue(event: any) {
this.userForm.patchValue({
state: event
})
}
Now in controls you have value A or B
Of course, "Fagner Antunes Dornelles" is correct in its answer. But it seems to me that it is worth checking the registry branch itself in addition, or be sure of the part that is exactly there.
For example ("dirty hack"), i need to establish trust in the RMS infrastructure, otherwise when i open Word or Excel documents, i will be prompted for "Active Directory Rights Management Services". Here's how i can add remote trust to me servers in the enterprise infrastructure.
foreach (var strServer in listServer)
{
try
{
RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC\\{strServer}", false);
if (regCurrentUser == null)
throw new ApplicationException("Not found registry SubKey ...");
if (regCurrentUser.GetValueNames().Contains("UserConsent") == false)
throw new ApplicationException("Not found value in SubKey ...");
}
catch (ApplicationException appEx)
{
Console.WriteLine(appEx);
try
{
RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC", true);
RegistryKey newKey = regCurrentUser.CreateSubKey(strServer, true);
newKey.SetValue("UserConsent", 1, RegistryValueKind.DWord);
}
catch(Exception ex)
{
Console.WriteLine($"{ex} Pipec kakoito ...");
}
}
}
There are multiple solution for the same.
run this query before creating or altering table.
SET @@global.innodb_large_prefix = 1;
this will set max key length to 3072 bytes
$(document).ready(function() {
$('#Button').click(function() {
$(this).addClass('active');
});
});
should do the trick. unless you're loading the button with ajax. In which case you could do:
$('#Button').live('click', function() {...
Also remember not to use the same id more than once in your html code.
List constructor accepts any data structure that implements Collection interface to be used to build a list.
To get all the keys from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<String> keys = new ArrayList<>(map.keySet());
To get all the values from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<Integer> values = new ArrayList<>(map.values());
You can initialize an array by writing actual values it holds in curly braces on the right hand side like:
String[] strArr = { "one", "two", "three"};
int[] numArr = { 1, 2, 3};
In the same manner two-dimensional array or array-of-arrays holds an array as a value, so:
String strArrayOfArrays = { {"a", "b", "c"}, {"one", "two", "three"} };
Your example shows exactly that
double m[][] = {
{0*0,1*0,2*0,3*0},
{0*1,1*1,2*1,3*1},
{0*2,1*2,2*2,3*2},
{0*3,1*3,2*3,3*3}
};
But also the multiplication of number will also be performed and its the same as:
double m[][] = { {0, 0, 0, 0}, {0, 1, 2, 3}, {0, 2, 4, 6}, {0, 3, 6, 9} };
As promised, here is my Cairo version. I scripted it with Lua, using lfs to walk the directories. I love these little challenges, as they allow me to explore APIs I wanted to dig for quite some time...
lfs and LuaCairo are both cross-platform, so it should work on other systems (tested on French WinXP Pro SP3).
I made a first version drawing file names as I walked the tree. Advantage: no memory overhead. Inconvenience: I have to specify the image size beforehand, so listings are likely to be cut off.
So I made this version, first walking the directory tree, storing it in a Lua table. Then, knowing the number of files, creating the canvas to fit (at least vertically) and drawing the names.
You can easily switch between PNG rendering and SVG one. Problem with the latter: Cairo generates it at low level, drawing the letters instead of using SVG's text capability. Well, at least, it guarantees accurate rending even on systems without the font. But the files are bigger... Not really a problem if you compress it after, to have a .svgz file.
Or it shouldn't be too hard to generate the SVG directly, I used Lua to generate SVG in the past.
-- LuaFileSystem <http://www.keplerproject.org/luafilesystem/>
require"lfs"
-- LuaCairo <http://www.dynaset.org/dogusanh/>
require"lcairo"
local CAIRO = cairo
local PI = math.pi
local TWO_PI = 2 * PI
--~ local dirToList = arg[1] or "C:/PrgCmdLine/Graphviz"
--~ local dirToList = arg[1] or "C:/PrgCmdLine/Tecgraf"
local dirToList = arg[1] or "C:/PrgCmdLine/tcc"
-- Ensure path ends with /
dirToList = string.gsub(dirToList, "([^/])$", "%1/")
print("Listing: " .. dirToList)
local fileNb = 0
--~ outputType = 'svg'
outputType = 'png'
-- dirToList must have a trailing slash
function ListDirectory(dirToList)
local dirListing = {}
for file in lfs.dir(dirToList) do
if file ~= ".." and file ~= "." then
local fileAttr = lfs.attributes(dirToList .. file)
if fileAttr.mode == "directory" then
dirListing[file] = ListDirectory(dirToList .. file .. '/')
else
dirListing[file] = ""
end
fileNb = fileNb + 1
end
end
return dirListing
end
--dofile[[../Lua/DumpObject.lua]] -- My own dump routine
local dirListing = ListDirectory(dirToList)
--~ print("\n" .. DumpObject(dirListing))
print("Found " .. fileNb .. " files")
--~ os.exit()
-- Constants to change to adjust aspect
local initialOffsetX = 20
local offsetY = 50
local offsetIncrementX = 20
local offsetIncrementY = 12
local iconOffset = 10
local width = 800 -- Still arbitrary
local titleHeight = width/50
local height = offsetIncrementY * (fileNb + 1) + titleHeight
local outfile = "CairoDirTree." .. outputType
local ctxSurface
if outputType == 'svg' then
ctxSurface = cairo.SvgSurface(outfile, width, height)
else
ctxSurface = cairo.ImageSurface(CAIRO.FORMAT_RGB24, width, height)
end
local ctx = cairo.Context(ctxSurface)
-- Display a file name
-- file is the file name to display
-- offsetX is the indentation
function DisplayFile(file, bIsDir, offsetX)
if bIsDir then
ctx:save()
ctx:select_font_face("Sans", CAIRO.FONT_SLANT_NORMAL, CAIRO.FONT_WEIGHT_BOLD)
ctx:set_source_rgb(0.5, 0.0, 0.7)
end
-- Display file name
ctx:move_to(offsetX, offsetY)
ctx:show_text(file)
if bIsDir then
ctx:new_sub_path() -- Position independent of latest move_to
-- Draw arc with absolute coordinates
ctx:arc(offsetX - iconOffset, offsetY - offsetIncrementY/3, offsetIncrementY/3, 0, TWO_PI)
-- Violet disk
ctx:set_source_rgb(0.7, 0.0, 0.7)
ctx:fill()
ctx:restore() -- Restore original settings
end
-- Increment line offset
offsetY = offsetY + offsetIncrementY
end
-- Erase background (white)
ctx:set_source_rgb(1.0, 1.0, 1.0)
ctx:paint()
--~ ctx:set_line_width(0.01)
-- Draw in dark blue
ctx:set_source_rgb(0.0, 0.0, 0.3)
ctx:select_font_face("Sans", CAIRO.FONT_SLANT_NORMAL, CAIRO.FONT_WEIGHT_BOLD)
ctx:set_font_size(titleHeight)
ctx:move_to(5, titleHeight)
-- Display title
ctx:show_text("Directory tree of " .. dirToList)
-- Select font for file names
ctx:select_font_face("Sans", CAIRO.FONT_SLANT_NORMAL, CAIRO.FONT_WEIGHT_NORMAL)
ctx:set_font_size(10)
offsetY = titleHeight * 2
-- Do the job
function DisplayDirectory(dirToList, offsetX)
for k, v in pairs(dirToList) do
--~ print(k, v)
if type(v) == "table" then
-- Sub-directory
DisplayFile(k, true, offsetX)
DisplayDirectory(v, offsetX + offsetIncrementX)
else
DisplayFile(k, false, offsetX)
end
end
end
DisplayDirectory(dirListing, initialOffsetX)
if outputType == 'svg' then
cairo.show_page(ctx)
else
--cairo.surface_write_to_png(ctxSurface, outfile)
ctxSurface:write_to_png(outfile)
end
ctx:destroy()
ctxSurface:destroy()
print("Found " .. fileNb .. " files")
Of course, you can change the styles. I didn't draw the connection lines, I didn't saw it as necessary. I might add them optionally later.
THIS SOLUTION WORKS
You do not need to map manually even if you dont have a PK. You just need to tell the EF that one of your columns is index and index column is not nullable.
To do this you can add a row number to your view with isNull function like the following
select
ISNULL(ROW_NUMBER() OVER (ORDER BY xxx), - 9999) AS id
from a
ISNULL(id, number)
is the key point here because it tells the EF that this column can be primary key
Add the indent
parameter to json.dumps
data = {'this': ['has', 'some', 'things'],
'in': {'it': 'with', 'some': 'more'}}
print(json.dumps(data, indent=4))
Also note that, you can simply use json.dump
with the open jsonfile
:
json.dump(data, jsonfile)
The following test works in Chrome 16 (dev branch) on X86 and Chrome 15 on Mac OSX Lion
I shall refer to the same sample of data as posted in the question:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
print('The original data frame is: \n{}'.format(df))
Running this code will give you
The original data frame is:
A B C D
0 0.494824 -0.328480 0.818117 0.100290
1 0.239037 0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856 0.359811 -0.345560
3 -0.070814 -0.394711 0.081697 -1.178845
4 -1.638063 1.498027 -0.609325 0.882594
5 -0.510217 0.500475 1.039466 0.187076
6 1.116529 0.912380 0.869323 0.119459
7 -1.046507 0.507299 -0.373432 -1.024795
Now you wish to append a new row to this data frame, which doesn't need to be copy of any other row in the data frame. @Alon suggested an interesting approach to use df.loc
to append a new row with different index. The issue, however, with this approach is if there is already a row present at that index, it will be overwritten by new values. This is typically the case for datasets when row index is not unique, like store ID in transaction datasets. So a more general solution to your question is to create the row, transform the new row data into a pandas series, name it to the index you want to have and then append it to the data frame. Don't forget to overwrite the original data frame with the one with appended row. The reason is df.append
returns a view of the dataframe and does not modify its contents. Following is the code:
row = pd.Series({'A':10,'B':20,'C':30,'D':40},name=3)
df = df.append(row)
print('The new data frame is: \n{}'.format(df))
Following would be the new output:
The new data frame is:
A B C D
0 0.494824 -0.328480 0.818117 0.100290
1 0.239037 0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856 0.359811 -0.345560
3 -0.070814 -0.394711 0.081697 -1.178845
4 -1.638063 1.498027 -0.609325 0.882594
5 -0.510217 0.500475 1.039466 0.187076
6 1.116529 0.912380 0.869323 0.119459
7 -1.046507 0.507299 -0.373432 -1.024795
3 10.000000 20.000000 30.000000 40.000000
Try running mongod
before mongo
.
sudo /usr/sbin/mongod
on my opensuse
This solved my problem,
First, is 40 collisions for 130 words hashed to 0..99 bad? You can't expect perfect hashing if you are not taking steps specifically for it to happen. An ordinary hash function won't have fewer collisions than a random generator most of the time.
A hash function with a good reputation is MurmurHash3.
Finally, regarding the size of the hash table, it really depends what kind of hash table you have in mind, especially, whether buckets are extensible or one-slot. If buckets are extensible, again there is a choice: you choose the average bucket length for the memory/speed constraints that you have.
USAGE: thisfile.php?dir=./path/to/folder (After zipping, it starts download too:)
<?php
$exclude_some_files=
array(
'mainfolder/folder1/filename.php',
'mainfolder/folder5/otherfile.php'
);
//***************built from https://gist.github.com/ninadsp/6098467 ******
class ModifiedFlxZipArchive extends ZipArchive {
public function addDirDoo($location, $name , $prohib_filenames=false) {
if (!file_exists($location)) { die("maybe file/folder path incorrect");}
$this->addEmptyDir($name);
$name .= '/';
$location.= '/';
$dir = opendir ($location); // Read all Files in Dir
while ($file = readdir($dir)){
if ($file == '.' || $file == '..') continue;
if (!in_array($name.$file,$prohib_filenames)){
if (filetype( $location . $file) == 'dir'){
$this->addDirDoo($location . $file, $name . $file,$prohib_filenames );
}
else {
$this->addFile($location . $file, $name . $file);
}
}
}
}
public function downld($zip_name){
ob_get_clean();
header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=" . basename($zip_name) . ";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($zip_name));
readfile($zip_name);
}
}
//set memory limits
set_time_limit(3000);
ini_set('max_execution_time', 3000);
ini_set('memory_limit','100M');
$new_zip_filename='down_zip_file_'.rand(1,1000000).'.zip';
// Download action
if (isset($_GET['dir'])) {
$za = new ModifiedFlxZipArchive;
//create an archive
if ($za->open($new_zip_filename, ZipArchive::CREATE)) {
$za->addDirDoo($_GET['dir'], basename($_GET['dir']), $exclude_some_files); $za->close();
}else {die('cantttt');}
if (isset($_GET['dir'])) {
$za = new ModifiedFlxZipArchive;
//create an archive
if ($za->open($new_zip_filename, ZipArchive::CREATE)) {
$za->addDirDoo($_GET['dir'], basename($_GET['dir']), $exclude_some_files); $za->close();
}else {die('cantttt');}
//download archive
//on the same execution,this made problems in some hostings, so better redirect
//$za -> downld($new_zip_filename);
header("location:?fildown=".$new_zip_filename); exit;
}
if (isset($_GET['fildown'])){
$za = new ModifiedFlxZipArchive;
$za -> downld($_GET['fildown']);
}
?>
You need to compile and link all your source files together:
g++ main.c function_file.c
I came across this question because I was getting this error using the Sideload Wonder Machine to install apps to my actual phone. I found the problem was that I had multiple .apk files in the /payload directory. I thought this was something that was supported, but when I removed all but one .apk, the error went away.
Most of bootstrap datepickers as I write this answer are rather buggy when included in Bootstrap 4. In my view the least code adding solution is a jQuery plugin. I used this one https://plugins.jquery.com/datetimepicker/ - you can see its usage here: https://xdsoft.net/jqplugins/datetimepicker/ It sure is not as smooth as the whole BS interface, but it only requires its css and js files along with jQuery which is already included in bootstrap.
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">
<solid android:color="@color/colorAccent" />
<corners
android:bottomLeftRadius="500dp"
android:bottomRightRadius="500dp"
android:topLeftRadius="500dp"
android:topRightRadius="500dp" />
</shape>
Now, in which element you want to use this shape just add:
android:background="@drawable/custom_round_ui_shape"
Create a new XML in drawable named "custom_round_ui_shape"