If you are using JDK 1.6 or above, You can use jmap
command to take a heap Dump of a Java process, condition is you should known ProcessID.
If you are on Windows Machine, you can use Task Manager to get PID. For Linux machine you can use varieties of command like ps -A | grep java
or netstat -tupln | grep java
or top | grep java
, depends on your application.
Then you can use the command like jmap -dump:format=b,file=sample_heap_dump.hprof 1234
where 1234 is PID.
There are varieties of tool available to interpret the hprof file. I will recommend Oracle's visualvm tool, which is simple to use.
Generally speaking, for boolean
or bit
data types, you would use 0
or 1
like so:
UPDATE tbl SET bitCol = 1 WHERE bitCol = 0
See also:
A dummy answer :-
I think explanation is given in above answer, so i am just gonna tell you where to use STRONG
and where to use WEAK
:
Use of Weak
:-
1. Delegates
2. Outlets
3. Subviews
4. Controls, etc.
Use of Strong
:-
Remaining everywhere which is not included in WEAK
.
It's not a good coding to put PHP code into CSS
body
{
background-image:url('bg.png');
}
that's it
Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.
How to check that Intel VT-x is supported in CPU:
Open Terminal application from Application/Utilities
Copy/paste command bellow
sysctl -a | grep machdep.cpu.features
Mac:~ user$ sysctl -a | grep machdep.cpu.features
kern.exec: unknown type returned
machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM
If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.
Refer to this link on Apple.com to enable hardware support for virtualization:
You need to use the autoGenerate
property
Your primary key annotation should be like this:
@PrimaryKey(autoGenerate = true)
Reference for PrimaryKey.
The bootstrap docs says about this:
Requires custom widths Inputs, selects, and textareas are 100% wide by default in Bootstrap. To use the inline form, you'll have to set a width on the form controls used within.
The default width of 100% as all form elements gets when they got the class form-control
didn't apply if you use the form-inline
class on your form.
You could take a look at the bootstrap.css (or .less, whatever you prefer) where you will find this part:
.form-inline {
// Kick in the inline
@media (min-width: @screen-sm-min) {
// Inline-block all the things for "inline"
.form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
// In navbar-form, allow folks to *not* use `.form-group`
.form-control {
display: inline-block;
width: auto; // Prevent labels from stacking above inputs in `.form-group`
vertical-align: middle;
}
// Input groups need that 100% width though
.input-group > .form-control {
width: 100%;
}
[...]
}
}
Maybe you should take a look at input-groups, since I guess they have exactly the markup you want to use (working fiddle here):
<div class="row">
<div class="col-lg-12">
<div class="input-group input-group-lg">
<input type="text" class="form-control input-lg" id="search-church" placeholder="Your location (City, State, ZIP)">
<span class="input-group-btn">
<button class="btn btn-default btn-lg" type="submit">Search</button>
</span>
</div>
</div>
</div>
In Wordpress jQuery.noConflict()
is called on the jQuery file it includes (scroll to the bottom of the file it's including for jQuery to see this), which means $
doesn't work, but jQuery
does, so your code should look like this:
<script type="text/javascript">
jQuery(function($) {
for(var i=0; i <= 20; i++)
$("ol li:nth-child(" + i + ")").addClass('olli' + i);
});
</script>
SHOW CREATE PROCEDURE <name>
Returns the text of a previously defined stored procedure that was created using the CREATE PROCEDURE
statement. Swap PROCEDURE
for FUNCTION
for a stored function.
Another option is not to start the async task until the dialog is attached to the window by overriding onAttachedToWindow() on the dialog, that way it is always dismissible.
This works for me and you don't need the inline script:
Javascript:
$(document).ready(function() {
$('.showme').bind('click', function() {
var id=$(this).attr("id");
var num=$(this).attr("class");
var poststr="request="+num+"&moreinfo="+id;
$.ajax({
url:"testme.php",
cache:0,
data:poststr,
success:function(result){
document.getElementById("stuff").innerHTML=result;
}
});
});
});
HTML:
<div class='request_1 showme' id='rating_1'>More stuff 1</div>
<div class='request_2 showme' id='rating_2'>More stuff 2</div>
<div class='request_3 showme' id='rating_3'>More stuff 3</div>
<div id="stuff">Here is some stuff that will update when the links above are clicked</div>
The request is sent to testme.php:
header("Cache-Control: no-cache");
header("Pragma: nocache");
$request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']);
$request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']);
if($request_id=="1")
{
echo "show 1";
}
elseif($request_id=="2")
{
echo "show 2";
}
else
{
echo "show 3";
}
var campaignTitle= CKEDITOR.instances['CampaignTitle'].getData();
import requests
import re
def getMyExtIp():
try:
res = requests.get("http://whatismyip.org")
myIp = re.compile('(\d{1,3}\.){3}\d{1,3}').search(res.text).group()
if myIp != "":
return myIp
except:
pass
return "n/a"
Perhaps this will help someone, as the error message is extremely unhelpful, and I had gone through all of the standard permission steps numerous times to no avail.
Docker occasionally leaves ghost environment variables in place that block access, despite your system otherwise being correctly set up. The following shell commands may make it accessible again, if you have had it running at one point and it just stopped cooperating after a reboot:
unset DOCKER_HOST
unset DOCKER_TLS_VERIFY
unset DOCKER_TLS_PATH
docker ps
I had a previously working docker install, and after rebooting my laptop it simply refused to work. Was correctly added to the docker user group, had the correct permissions on the socket, etc, but could still not run docker login
, docker run ...
, etc. This fixed it for me. Unfortunately I have to run this on each reboot. This is mentioned on a couple of github issues also as a workaround, although it seems like a bug that this is a persistent barrier to correct operation of Docker (note: I am on Arch Linux, not OSX, but this was the same issue for me).
Nothing was working for me but then I checked here. I ran that command qc sc mysql57
and copied the value of BINARY_PATH_NAME
from it. After that I checked this and changed the value of lower_case_table_names
from 0 to 2 in my.ini
file. Then in the command prompt, I ran this command - << BINARY_PATH_NAME >> --install-manual
. After that, I started the MySQL57 service and it worked.
This can also be done in the GUI. Here's an example adding a multi-column unique constraint to an existing table.
Click OK in each window and you're done.
A char
variable is actually an 8-bit integral value. It will have values from 0
to 255
. These are ASCII codes. 0
stands for the C-null character, and 255
stands for an empty symbol.
So, when you write the following assignment:
char a = 'a';
It is the same thing as:
char a = 97;
So, you can compare two char
variables using the >
, <
, ==
, <=
, >=
operators:
char a = 'a';
char b = 'b';
if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);
Based on Jakub's answer you can configure the following git aliases for convenience:
accept-ours = "!f() { git checkout --ours -- \"${@:-.}\"; git add -u \"${@:-.}\"; }; f"
accept-theirs = "!f() { git checkout --theirs -- \"${@:-.}\"; git add -u \"${@:-.}\"; }; f"
They optionally take one or several paths of files to resolve and default to resolving everything under the current directory if none are given.
Add them to the [alias]
section of your ~/.gitconfig
or run
git config --global alias.accept-ours '!f() { git checkout --ours -- "${@:-.}"; git add -u "${@:-.}"; }; f'
git config --global alias.accept-theirs '!f() { git checkout --theirs -- "${@:-.}"; git add -u "${@:-.}"; }; f'
According to Microsoft's MSDN, the lock is equivalent to:
object __lockObj = x;
bool __lockWasTaken = false;
try
{
System.Threading.Monitor.Enter(__lockObj, ref __lockWasTaken);
// Your code...
}
finally
{
if (__lockWasTaken) System.Threading.Monitor.Exit(__lockObj);
}
If you need to create locks in runtime, you can use open source DynaLock. You can create new locks in run-time and specify boundaries to the locks with context concept.
DynaLock is open-source and source code is available at GitHub
I like the idea from Jakub Jirutka to use Spring Expression Language. If you don't want to add another library/dependency (assuming that you already use Spring), here is a simplified implementation of his idea.
The constraint:
@Constraint(validatedBy=ExpressionAssertValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExpressionAssert {
String message() default "expression must evaluate to true";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String value();
}
The validator:
public class ExpressionAssertValidator implements ConstraintValidator<ExpressionAssert, Object> {
private Expression exp;
public void initialize(ExpressionAssert annotation) {
ExpressionParser parser = new SpelExpressionParser();
exp = parser.parseExpression(annotation.value());
}
public boolean isValid(Object value, ConstraintValidatorContext context) {
return exp.getValue(value, Boolean.class);
}
}
Apply like this:
@ExpressionAssert(value="pass == passVerify", message="passwords must be same")
public class MyBean {
@Size(min=6, max=50)
private String pass;
private String passVerify;
}
So, for future reference for anybody who doesn't want to spend two days searching the internet to figure this out, when you encode byte arrays into QR Codes, you have to use the ISO-8859-1
character set, not UTF-8
.
I wanted to detect left and right swipe only, but trigger the action only when the touch event ends, so I slightly modified the @givanse's great answer to do that.
Why to do that? If for example, while swiping, the user notices he finally doesn't want to swipe, he can move his finger at the original position (a very popular "dating" phone application does this ;)), and then the "swipe right" event is cancelled.
So in order to avoid a "swipe right" event just because there is a 3px difference horizontally, I added a threshold under which an event is discarded: in order to have a "swipe right" event, the user has to swipe of at least 1/3 of the browser width (of course you can modify this).
All these small details enhance the user experience.
Note that currently, a "touch pinch zoom" might be detected as a swipe if one of the two fingers does a big horizontal move during the pinch zoom.
Here is the (Vanilla JS) code:
var xDown = null, yDown = null, xUp = null, yUp = null;
document.addEventListener('touchstart', touchstart, false);
document.addEventListener('touchmove', touchmove, false);
document.addEventListener('touchend', touchend, false);
function touchstart(evt) { const firstTouch = (evt.touches || evt.originalEvent.touches)[0]; xDown = firstTouch.clientX; yDown = firstTouch.clientY; }
function touchmove(evt) { if (!xDown || !yDown ) return; xUp = evt.touches[0].clientX; yUp = evt.touches[0].clientY; }
function touchend(evt) {
var xDiff = xUp - xDown, yDiff = yUp - yDown;
if ((Math.abs(xDiff) > Math.abs(yDiff)) && (Math.abs(xDiff) > 0.33 * document.body.clientWidth)) {
if (xDiff < 0)
document.getElementById('leftnav').click();
else
document.getElementById('rightnav').click();
}
xDown = null, yDown = null;
}
Sharing a few functions which I created for dates:
Please note that I wanted to get time for a particular location (not just UTC time). If you want UTC time, just remove loc variable and .In(loc) function call.
func GetTimeStamp() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
t := time.Now().In(loc)
return t.Format("20060102150405")
}
func GetTodaysDate() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("2006-01-02")
}
func GetTodaysDateTime() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("2006-01-02 15:04:05")
}
func GetTodaysDateTimeFormatted() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("Jan 2, 2006 at 3:04 PM")
}
func GetTimeStampFromDate(dtformat string) string {
form := "Jan 2, 2006 at 3:04 PM"
t2, _ := time.Parse(form, dtformat)
return t2.Format("20060102150405")
}
Polymorphism relates to the ability of a language to have different object treated uniformly by using a single interfaces; as such it is related to overriding, so the interface (or the base class) is polymorphic, the implementor is the object which overrides (two faces of the same medal)
anyway, the difference between the two terms is better explained using other languages, such as c++: a polymorphic object in c++ behaves as the java counterpart if the base function is virtual, but if the method is not virtual the code jump is resolved statically, and the true type not checked at runtime so, polymorphism include the ability for an object to behave differently depending on the interface used to access it; let me make an example in pseudocode:
class animal {
public void makeRumor(){
print("thump");
}
}
class dog extends animal {
public void makeRumor(){
print("woff");
}
}
animal a = new dog();
dog b = new dog();
a.makeRumor() -> prints thump
b.makeRumor() -> prints woff
(supposing that makeRumor is NOT virtual)
java doesn't truly offer this level of polymorphism (called also object slicing).
animal a = new dog(); dog b = new dog();
a.makeRumor() -> prints thump
b.makeRumor() -> prints woff
on both case it will only print woff.. since a and b is refering to class dog
I recommend that you get in the habit, right now, of using ANSI-style joins, meaning you should use the INNER JOIN
, LEFT OUTER JOIN
, RIGHT OUTER JOIN
, FULL OUTER JOIN
, and CROSS JOIN
elements in your SQL statements rather than using the "old-style" joins where all the tables are named together in the FROM
clause and all the join conditions are put in the the WHERE
clause. ANSI-style joins are easier to understand and less likely to be miswritten and/or misinterpreted than "old-style" joins.
I'd rewrite your query as:
SELECT bc.firstname,
bc.lastname,
b.title,
TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date",
p.publishername
FROM BOOK_CUSTOMER bc
INNER JOIN books b
ON b.BOOK_ID = bc.BOOK_ID
INNER JOIN book_order bo
ON bo.BOOK_ID = b.BOOK_ID
INNER JOIN publisher p
ON p.PUBLISHER_ID = b.PUBLISHER_ID
WHERE p.publishername = 'PRINTING IS US';
Share and enjoy.
Change the h1.textContent
to h1.innerHTML
and use <br>
to go to the new line.
Here you can find a good example of how to format Y-Axis value.
Also, you can use scaleLabel : "<%=value%>"
that you mentioned, It basically means that everything between <%=
and %>
tags will be treated as javascript code (i.e you can use if
statments...)
if (/(^|;)\s*visited=/.test(document.cookie)) {
alert("Hello again!");
} else {
document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
alert("This is your first time!");
}
is one way to do it. Note that document.cookie
is a magic property, so you don't have to worry about overwriting anything, either.
There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage
and friends are convenient and useful.
You need to use overflow option like below:
.nav{
max-height: 300px;
overflow-y: scroll;
}
Change the height according to amount of items you need to show
$('.input').on('focus', function(){
$(this).val('');
});
$('[type="submit"]').on('click', function(){
$('.input').val('');
});
A general tip , if you get confused by any of new JS syntax and how it will compile , you can check babel. For example copying your code in babel and selecting the es2015 preset will give an output like this
handleChange = function handleChange(field) {
return function (e) {
e.preventDefault();
// Do something here
};
};
None of the answers here worked for me out of the box, here is what worked for me:
Create pipes/keys.ts
with contents:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform
{
transform(value:any, args:string[]): any {
let keys:any[] = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}
Add to app.module.ts
(Your main module):
import { KeysPipe } from './pipes/keys';
and then add to your module declarations array something like this:
@NgModule({
declarations: [
KeysPipe
]
})
export class AppModule {}
Then in your view template you can use something like this:
<option *ngFor="let entry of (myData | keys)" value="{{ entry.key }}">{{ entry.value }}</option>
Here is a good reference I found if you want to read more.
I had the same problem: the error was File not found
, while opening HTML
files in chrome, but I resolved it as follows:
BEFORE:
1) I saved a html file abc.html
in a folder name C#
.
2) When I was opening the abc.html
in Google Chrome, it was showing error as "file not found". But it was working fine on Firefox and Internet Explorer.
AFTER:
3) What I did then is, I simply changed the folder name C#
to csharp
without space and re opened it in Chrome. It worked.
4) The moral is: Make sure you don't give any space in a folder name as some browsers don't support it.
Sometime I will try 1000 times in my onDestroy()/contextDestroyed()
@Override
protected void onDestroy() {
boolean retry = true;
int counter = 0;
while(retry && counter<1000)
{
counter++;
try{thread.setRunnung(false);
thread.join();
retry = false;
thread = null; //garbage can coll
}catch(InterruptedException e){e.printStackTrace();}
}
}
Usually SelectedItems
returns either a collection, an array or an IQueryable
.
Either way you can access items via the index as with an array:
String text = listView1.SelectedItems[0].Text;
By the way, you can save an item you want to look at into a variable, and check its structure in the locals after setting a breakpoint.
a=123
if [ `echo $a | tr -d [:digit:] | wc -w` -eq 0 ]
then
echo numeric
else
echo ng
fi
numeric
a=12s3
if [ `echo $a | tr -d [:digit:] | wc -w` -eq 0 ]
then
echo numeric
else
echo ng
fi
ng
I had a similar issue, no videos would play in Chrome. Tried installing beta 64bit, going back to Chrome 32bit release.
The only thing that worked for me was updating my video drivers.
I have the NVIDIA GTS 240. Downloaded, installed the drivers and restarted and Chrome 38.0.2125.77 beta-m (64-bit) starting playing HTML5 videos again on youtube, vimeo and others. Hope this helps anyone else.
// simple example using the concept of setInterval
$(document).ready(function(){
var g = $('.jumping');
function blink(){
g.animate({ 'left':'50px'
}).animate({
'left':'20px'
},1000)
}
setInterval(blink,1500);
});
The original code works fine for reading and separating the csv file data but you need to change the data type from csv to text.
When using NOT IN you should ensure that none of the values are NULL:
SELECT mac, creation_date
FROM logs
WHERE logs_type_id=11
AND mac NOT IN (
SELECT mac
FROM consols
WHERE mac IS NOT NULL -- add this
)
import android.content.Context;
import android.content.ContentResolver;
context = (Context)this;
ContentResolver result = (ContentResolver)context.getContentResolver();
After lots and lots of installing and uninstalling for a whole day and trying every packages for every answers in here, the only thing that worked for me was:
This somehow install something that is needed for Wamp as well.
The usual way to use assertRaises
is to call a function:
self.assertRaises(TypeError, test_function, args)
to test that the function call test_function(args) raises a TypeError.
The problem with self.testListNone[:1]
is that Python evaluates the expression immediately, before the assertRaises
method is called. The whole reason why test_function
and args
is passed as separate arguments to self.assertRaises
is to allow assertRaises
to call test_function(args)
from within a try...except
block, allowing assertRaises
to catch the exception.
Since you've defined self.testListNone = None
, and you need a function to call, you might use operator.itemgetter like this:
import operator
self.assertRaises(TypeError, operator.itemgetter, (self.testListNone,slice(None,1)))
since
operator.itemgetter(self.testListNone,slice(None,1))
is a long-winded way of saying self.testListNone[:1]
, but which separates the function (operator.itemgetter
) from the arguments.
I suspect Steven A. Lowe's rolled up newspaper therapy is required for the designer of the original data structure.
As an aside, GUIDs as a primary key can be a performance hog. I wouldn't recommend it.
I followed tim peterson's instructions but I created a local branch for my changes. However, after pushing I was not seeing the new branch in GitHub. The solution was to add -u to the push command:
git push -u origin <branch>
as simple as:
find . -mtime -1 | xargs tar --no-recursion -czf myfile.tgz
where find . -mtime -1
will select all the files in (recursively) current directory modified day before. you can use fractions, for example:
find . -mtime -1.5 | xargs tar --no-recursion -czf myfile.tgz
For me what worked by combining all the posts I have read is:
1.Enable OLE automation - if not enabled
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
2.Create a folder where the generated files will be stored:
C:\GREGTESTING
3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
CREATE TABLE [dbo].[Document](
[Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[Extension] [varchar](50) NULL,
[FileName] [varchar](200) NULL,
[Doc_Content] [varbinary](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)
Important note!
Don't forget to add in Doc_Content column the varbinary of file you want to generate!
4.Run the below script
DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max)
, @fPath varchar(max)
, @folderPath varchar(max)
--Get Data into temp Table variable so that we can iterate over it
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num] varchar(100) , [FileName] varchar(100), [Doc_Content] varBinary(max) )
INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM [dbo].[Document]
SELECT @i = COUNT(1) FROM @Doctable
WHILE @i >= 1
BEGIN
SELECT
@data = [Doc_Content],
@fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
@folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i
EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+ @fPath
--Reset the variables for next use
SELECT @data = NULL
, @init = NULL
, @fPath = NULL
, @folderPath = NULL
SET @i -= 1
END
In the default constructor (and any non-default ones if you have any too of course):
public foo() {
Bar = "bar";
}
This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.
The preferred method is actually:
@System.Web.Configuration.WebConfigurationManager.AppSettings["myKey"]
It also doesn't need a reference to the ConfigurationManager assembly, it's already in System.Web.
Tried couple solutions from many sources but all seemed like too much trouble. Finally I found the easiest one :)
If you're not yet familiar with zsh and oh-my-zsh then install it. You will love it :)
Then edit .zshrc
vim ~/.zshrc
find plugins
section and update it to use ssh-agent
like so:
plugins=(ssh-agent git)
And that's all! You'll have ssh-agent
up and running every time you start your shell
The conventional syntax is d[key] = value
, but if your keyboard is missing the square bracket keys you could also do:
d.__setitem__(key, value)
In fact, defining __getitem__
and __setitem__
methods is how you can make your own class support the square bracket syntax. See https://python.developpez.com/cours/DiveIntoPython/php/endiveintopython/object_oriented_framework/special_class_methods.php
This is what worked for me: https://github.com/bumptech/glide/wiki/Custom-targets#overriding-default-behavior
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.transition.Transition;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
...
Glide.with(yourFragment)
.load("yourUrl")
.asBitmap()
.into(new BitmapImageViewTarget(yourImageView) {
@Override
public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> anim) {
super.onResourceReady(bitmap, anim);
Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
// Here's your generated palette
Palette.Swatch swatch = palette.getDarkVibrantSwatch();
int color = palette.getDarkVibrantColor(swatch.getTitleTextColor());
}
});
}
});
Add your proxy preferences into .curlrc
proxy = 1.2.3.4
noproxy = .dev,localhost,127.0.0.1
This make all dev domains and local machine request ignore the proxy.
In the PHP file first you need to register the session
<? session_start();
$_SESSION['id'] = $userData['user_id'];?>
And in each page of your php application you can retrive the session id
<? session_start()
id = $_SESSION['id'];
?>
To install wheel packages in python 2.7x:
Install python 2.7x (i would recommend python 2.78) - download the appropriate python binary for your version of windows . You can download python 2.78 at this site https://www.python.org/download/releases/2.7.8/ -I would recommend installing the graphical Tk module, and including python 2.78 in the windows path (environment variables) during installation.
Install get-pip.py and setuptools Download the installer at https://bootstrap.pypa.io/get-pip.py Double click the above file to run it. It will install pip and setuptools [or update them, if you have an earlier version of either]
-Double click the above file and wait - it will open a black window and print will scroll across the screen as it downloads and installs [or updates] pip and setuptools --->when it finishes the window will close.
A-type cd c:\python27\scripts [or cd \scripts ]
B-type pip install -u Eg to install pyside, type pip install -u pyside
Wait - it will state 'downloading PySide or -->it will download and install the appropriate version of the python package [the one that corresponds to your version of python and windows.]
Note - if you have downloaded the .whl file and saved it locally on your hard drive, type in
pip install --no-index --find-links=localpathtowheelfile packagename
**to install a previously downloaded wheel package you need to type in the following command pip install --no-index --find-links=localpathtowheelfile packagename
sed
If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed
command once the (X)HTML has been created from Markdown:
sed -i 's|href="http|target="_blank" href="http|g' index.html
This can be further automated in a single workflow when a Makefile
with build instructions is employed.
PS: This answer was written at a time when extension link_attributes
was not yet available in Pandoc.
You're returning the address of a local variable allocated on the stack. When your function returns, the storage for all local variables (such as wc
) is deallocated and is subject to being immediately overwritten by something else.
To fix this, you can pass the size of the buffer to GetWC
, but then you've got pretty much the same interface as mbstowcs
itself. Or, you could allocate a new buffer inside GetWC
and return a pointer to that, leaving it up to the caller to deallocate the buffer.
You can use old C-style programming to do the job. This will require little knowledge about C++. Good for beginners.
For modern C++ language you usually accomplish this through lambda, function objects, ... or algorithm: find
, find_if
, any_of
, for_each
, or the new for (auto& v : container) { }
syntax. find
class algorithm takes more lines of code. You may also write you own template find
function for your particular need.
Here is my sample code
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
using namespace std;
/**
* This is old C-like style. It is mostly gong from
* modern C++ programming. You can still use this
* since you need to know very little about C++.
* @param storeSize you have to know the size of store
* How many elements are in the array.
* @return the index of the element in the array,
* if not found return -1
*/
int in_array(const int store[], const int storeSize, const int query) {
for (size_t i=0; i<storeSize; ++i) {
if (store[i] == query) {
return i;
}
}
return -1;
}
void testfind() {
int iarr[] = { 3, 6, 8, 33, 77, 63, 7, 11 };
// for beginners, it is good to practice a looping method
int query = 7;
if (in_array(iarr, 8, query) != -1) {
cout << query << " is in the array\n";
}
// using vector or list, ... any container in C++
vector<int> vecint{ 3, 6, 8, 33, 77, 63, 7, 11 };
auto it=find(vecint.begin(), vecint.end(), query);
cout << "using find()\n";
if (it != vecint.end()) {
cout << "found " << query << " in the container\n";
}
else {
cout << "your query: " << query << " is not inside the container\n";
}
using namespace std::placeholders;
// here the query variable is bound to the `equal_to` function
// object (defined in std)
cout << "using any_of\n";
if (any_of(vecint.begin(), vecint.end(), bind(equal_to<int>(), _1, query))) {
cout << "found " << query << " in the container\n";
}
else {
cout << "your query: " << query << " is not inside the container\n";
}
// using lambda, here I am capturing the query variable
// into the lambda function
cout << "using any_of with lambda:\n";
if (any_of(vecint.begin(), vecint.end(),
[query](int val)->bool{ return val==query; })) {
cout << "found " << query << " in the container\n";
}
else {
cout << "your query: " << query << " is not inside the container\n";
}
}
int main(int argc, char* argv[]) {
testfind();
return 0;
}
Say this file is named 'testalgorithm.cpp' you need to compile it with
g++ -std=c++11 -o testalgorithm testalgorithm.cpp
Hope this will help. Please update or add if I have made any mistake.
@Sparr is right, but I guess you expected byte array like byte[]
in C#. It's the same solution as Sparr did but instead of HEX you expected int
presentation (range from 0 to 255) of each char
. You can do as follows:
$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog');
var_dump($byte_array); // $byte_array should be int[] which can be converted
// to byte[] in C# since values are range of 0 - 255
By using var_dump
you can see that elements are int
(not string
).
array(44) { [1]=> int(84) [2]=> int(104) [3]=> int(101) [4]=> int(32)
[5]=> int(113) [6]=> int(117) [7]=> int(105) [8]=> int(99) [9]=> int(107)
[10]=> int(32) [11]=> int(102) [12]=> int(111) [13]=> int(120) [14]=> int(32)
[15]=> int(106) [16]=> int(117) [17]=> int(109) [18]=> int(112) [19]=> int(101)
[20]=> int(100) [21]=> int(32) [22]=> int(111) [23]=> int(118) [24]=> int(101)
[25]=> int(114) [26]=> int(32) [27]=> int(116) [28]=> int(104) [29]=> int(101)
[30]=> int(32) [31]=> int(108) [32]=> int(97) [33]=> int(122) [34]=> int(121)
[35]=> int(32) [36]=> int(98) [37]=> int(114) [38]=> int(111) [39]=> int(119)
[40]=> int(110) [41]=> int(32) [42]=> int(100) [43]=> int(111) [44]=> int(103) }
Be careful: the output array is of 1-based index (as it was pointed out in the comment)
Sometimes NaNs or null values in data will generate this error with Numpy. If you are ingesting data from say, a CSV file or something like that, and then operating on the data using numpy arrays, the problem could have originated with your data ingest. You could try feeding your code a small set of data with known values, and see if you get the same result.
I find the easiest way is to double up on the quotes to handle a quote.
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)"
Some people like to use CHR(34)*:
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"
*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.
write this code up:
android:background="@color/colorAccent"
I think that's what you're looking for:
SELECT CASE WHEN BoolField05 = 1 THEN Status ELSE 'DELETED' END AS MyStatus, t1.*
FROM WorkItems t1
WHERE (TextField01, TimeStamp) IN(
SELECT TextField01, MAX(TimeStamp)
FROM WorkItems t2
GROUP BY t2.TextField01
)
AND TimeStamp > '2009-02-12 18:00:00'
If you're in Oracle or in MS SQL 2005 and above, then you could do:
SELECT *
FROM (
SELECT CASE WHEN BoolField05 = 1 THEN Status ELSE 'DELETED' END AS MyStatus, t1.*,
ROW_NUMBER() OVER (PARTITION BY TextField01 ORDER BY TimeStamp DESC) AS rn
FROM WorkItems t1
) to
WHERE rn = 1
, it's more efficient.
If you want to grant to both tables and views try:
SELECT DISTINCT
|| OWNER
|| '.'
|| TABLE_NAME
|| ' to db_user;'
FROM
ALL_TAB_COLS
WHERE
TABLE_NAME LIKE 'TABLE_NAME_%';
For just views try:
SELECT
'grant select on '
|| OWNER
|| '.'
|| VIEW_NAME
|| ' to REPORT_DW;'
FROM
ALL_VIEWS
WHERE
VIEW_NAME LIKE 'VIEW_NAME_%';
Copy results and execute.
I've been able to solve this by using a hack involving import *
. It even works for both named and default exports!
For a named export:
// dependency.js
export const doSomething = (y) => console.log(y)
// myModule.js
import { doSomething } from './dependency';
export default (x) => {
doSomething(x * 2);
}
// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';
describe('myModule', () => {
it('calls the dependency with double the input', () => {
dependency.doSomething = jest.fn(); // Mutate the named export
myModule(2);
expect(dependency.doSomething).toBeCalledWith(4);
});
});
Or for a default export:
// dependency.js
export default (y) => console.log(y)
// myModule.js
import dependency from './dependency'; // Note lack of curlies
export default (x) => {
dependency(x * 2);
}
// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';
describe('myModule', () => {
it('calls the dependency with double the input', () => {
dependency.default = jest.fn(); // Mutate the default export
myModule(2);
expect(dependency.default).toBeCalledWith(4); // Assert against the default
});
});
As Mihai Damian quite rightly pointed out below, this is mutating the module object of dependency
, and so it will 'leak' across to other tests. So if you use this approach you should store the original value and then set it back again after each test.
To do this easily with Jest, use the spyOn() method instead of jest.fn()
, because it supports easily restoring its original value, therefore avoiding before mentioned 'leaking'.
If JSON returned with following structure when records is an ArrayNode:
{}client
records[]
and you want to check if records node has something in it then you can do it using a method size();
if (recordNodes.get(i).size() != 0) {}
As a checkbox click = a checkbox change the following will also work:
<CheckBox Click="CheckBox_Click" />
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
// ... do some stuff
}
It has the additional advantage of working when IsThreeState="True"
whereas just handling Checked and Unchecked does not.
I have the same issue, but I use GitLab instead of Jenkins. The steps I had to do to get over the issue:
I realize that is more specific to my setup. But without doing all of the steps above I would still continue to get this error message
Return code is: 501 , ReasonPhrase:HTTPS Required
public class Student
{
public string Name { set; get; }
public int ID { set; get; }
}
class Program
{
static void Main(string[] args)
{
Student[] students =
{
new Student { Name="zoyeb" , ID=1},
new Student { Name="Siddiq" , ID=2},
new Student { Name="sam" , ID=3},
new Student { Name="james" , ID=4},
new Student { Name="sonia" , ID=5}
};
var studentCollection = from s in students select new { s.ID , s.Name};
foreach (var student in studentCollection)
{
Console.WriteLine(student.Name);
Console.WriteLine(student.ID);
}
}
}
With MSSQL you can do something like this:
declare @result varchar(500)
set @result = ''
select @result = @result + ModuleValue + ', '
from TableX where ModuleId = @ModuleId
First function: configured for italian time zone (+1, +2), switch dates: last sunday of march and october, return the difference between the current time zone and the datetime as parameter.
Returns:
current timezone < parameter timezone ==> +1
current timezone > parameter timezone ==> -1
else 0
The code is:
CREATE FUNCTION [dbo].[UF_ADJUST_OFFSET]
(
@dt_utc datetime2(7)
)
RETURNS INT
AS
BEGIN
declare @month int,
@year int,
@current_offset int,
@offset_since int,
@offset int,
@yearmonth varchar(8),
@changeoffsetdate datetime2(7)
declare @lastweek table(giorno datetime2(7))
select @current_offset = DATEDIFF(hh, GETUTCDATE(), GETDATE())
select @month = datepart(month, @dt_utc)
if @month < 3 or @month > 10 Begin Set @offset_since = 1 Goto JMP End
if @month > 3 and @month < 10 Begin Set @offset_since = 2 Goto JMP End
--If i'm here is march or october
select @year = datepart(yyyy, @dt_utc)
if @month = 3
Begin
Set @yearmonth = cast(@year as varchar) + '-03-'
Insert Into @lastweek Values(@yearmonth + '31 03:00:00.000000'),(@yearmonth + '30 03:00:00.000000'),(@yearmonth + '29 03:00:00.000000'),(@yearmonth + '28 03:00:00.000000'),
(@yearmonth + '27 03:00:00.000000'),(@yearmonth + '26 03:00:00.000000'),(@yearmonth + '25 03:00:00.000000')
--Last week of march
Select @changeoffsetdate = giorno From @lastweek Where datepart(weekday, giorno) = 1
if @dt_utc < @changeoffsetdate
Begin
Set @offset_since = 1
End Else Begin
Set @offset_since = 2
End
End
if @month = 10
Begin
Set @yearmonth = cast(@year as varchar) + '-10-'
Insert Into @lastweek Values(@yearmonth + '31 03:00:00.000000'),(@yearmonth + '30 03:00:00.000000'),(@yearmonth + '29 03:00:00.000000'),(@yearmonth + '28 03:00:00.000000'),
(@yearmonth + '27 03:00:00.000000'),(@yearmonth + '26 03:00:00.000000'),(@yearmonth + '25 03:00:00.000000')
--Last week of october
Select @changeoffsetdate = giorno From @lastweek Where datepart(weekday, giorno) = 1
if @dt_utc > @changeoffsetdate
Begin
Set @offset_since = 1
End Else Begin
Set @offset_since = 2
End
End
JMP:
if @current_offset < @offset_since Begin
Set @offset = 1
End Else if @current_offset > @offset_since Set @offset = -1 Else Set @offset = 0
Return @offset
END
Then the function that convert date
CREATE FUNCTION [dbo].[UF_CONVERT]
(
@dt_utc datetime2(7)
)
RETURNS datetime
AS
BEGIN
declare @offset int
Select @offset = dbo.UF_ADJUST_OFFSET(@dt_utc)
if @dt_utc >= '9999-12-31 22:59:59.9999999'
set @dt_utc = '9999-12-31 23:59:59.9999999'
Else
set @dt_utc = (SELECT DATEADD(mi, DATEDIFF(mi, GETUTCDATE(), GETDATE()), @dt_utc) )
if @offset <> 0
Set @dt_utc = dateadd(hh, @offset, @dt_utc)
RETURN @dt_utc
END
Yes, should try reinstall mysql, but use the --reinstall
flag to force a package reconfiguration. So the operating system service configuration is not skipped:
sudo apt --reinstall install mysql-server
For such a simple XML structure, you may not want to involve a full blown XML module. Consider a string template for the simplest structures, or Jinja for something a little more complex. Jinja can handle looping over a list of data to produce the inner xml of your document list. That is a bit trickier with raw python string templates
For a Jinja example, see my answer to a similar question.
Here is an example of generating your xml with string templates.
import string
from xml.sax.saxutils import escape
inner_template = string.Template(' <field${id} name="${name}">${value}</field${id}>')
outer_template = string.Template("""<root>
<doc>
${document_list}
</doc>
</root>
""")
data = [
(1, 'foo', 'The value for the foo document'),
(2, 'bar', 'The <value> for the <bar> document'),
]
inner_contents = [inner_template.substitute(id=id, name=name, value=escape(value)) for (id, name, value) in data]
result = outer_template.substitute(document_list='\n'.join(inner_contents))
print result
Output:
<root>
<doc>
<field1 name="foo">The value for the foo document</field1>
<field2 name="bar">The <value> for the <bar> document</field2>
</doc>
</root>
The downer of the template approach is that you won't get escaping of <
and >
for free. I danced around that problem by pulling in a util from xml.sax
I recently had this issue and I ran 'depends.exe' on the dll in question. It showed me that the dll was compiled in x86 while some of the dependencys were compiled in x64.
If you are still having troubles I would recommend using depends.exe.
You can check this with the return-value ssh gives you:
$ ssh -q user@downhost exit
$ echo $?
255
$ ssh -q user@uphost exit
$ echo $?
0
EDIT: Another approach would be to use nmap (you won't need to have keys or login-stuff):
$ a=`nmap uphost -PN -p ssh | grep open`
$ b=`nmap downhost -PN -p ssh | grep open`
$ echo $a
22/tcp open ssh
$ echo $b
(empty string)
But you'll have to grep the message (nmap does not use the return-value to show if a port was filtered, closed or open).
EDIT2:
If you're interested in the actual state of the ssh-port, you can substitute grep open
with egrep 'open|closed|filtered'
:
$ nmap host -PN -p ssh | egrep 'open|closed|filtered'
Just to be complete.
Are you including "stdlib.h" or "cstdlib" in this file? NULL is defined in stdlib.h/cstdlib
#include <stdlib.h>
or
#include <cstdlib> // This is preferrable for c++
That should do it:
FOR %%a IN (%Svcs%) DO (SC query %%a | FIND /i "RUNNING"
IF ERRORLEVEL 1 SC start %%a)
You could created sorted list from Values and rebuild the dictionary:
myDictionary={"two":"2", "one":"1", "five":"5", "1four":"4"}
newDictionary={}
sortedList=sorted(myDictionary.values())
for sortedKey in sortedList:
for key, value in myDictionary.items():
if value==sortedKey:
newDictionary[key]=value
Output: newDictionary={'one': '1', 'two': '2', '1four': '4', 'five': '5'}
Ok I know this for VBA but if you need to do this for a once off bulk delete you can use the following Excel functionality: http://blog.contextures.com/archives/2010/06/21/fast-way-to-find-and-delete-excel-rows/ Hope this helps anyone
Example looking for the string "paper":
During development / testing of new releases, the cache can be a problem because the browser, the server and even sometimes the 3G telco (if you do mobile deployment) will cache the static content (e.g. JS, CSS, HTML, img). You can overcome this by appending version number, random number or timestamp to the URL e.g: JSP: <script src="js/excel.js?time=<%=new java.util.Date()%>"></script>
In case you're running pure HTML (instead of server pages JSP, ASP, PHP) the server won't help you. In browser, links are loaded before the JS runs, therefore you have to remove the links and load them with JS.
// front end cache bust
var cacheBust = ['js/StrUtil.js', 'js/protos.common.js', 'js/conf.js', 'bootstrap_ECP/js/init.js'];
for (i=0; i < cacheBust.length; i++){
var el = document.createElement('script');
el.src = cacheBust[i]+"?v=" + Math.random();
document.getElementsByTagName('head')[0].appendChild(el);
}
You can use float:left in DIV or use SPAN tag, like
<div style="width:100px;float:left"> First </div>
<div> Second </div>
<br/>
or
<span style="width:100px;"> First </span>
<span> Second </span>
<br/>
In Java 8, the syntax for this simplifies greatly and can be used to accomplish this transformation succinctly.
Do note, you will need to change your field from a concrete implementation to the List
interface for this to work smoothly.
public class Wetland {
private String name;
private List<String> species;
public Wetland(String name, String[] speciesArr) {
this.name = name;
species = Arrays.stream(speciesArr)
.collect(Collectors.toList());
}
}
Make sure you have imported the correct package. If I remeber correctly there are two different packages for Autowiring. Should be :org.springframework.beans.factory.annotation.Autowired;
Also this looks wierd to me :
@ContextConfiguration("classpath*:conf/components.xml")
Here is an example that works fine for me :
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext_mock.xml" })
public class OwnerIntegrationTest {
@Autowired
OwnerService ownerService;
@Before
public void setup() {
ownerService.cleanList();
}
@Test
public void testOwners() {
Owner owner = new Owner("Bengt", "Karlsson", "Ankavägen 3");
owner = ownerService.createOwner(owner);
assertEquals("Check firstName : ", "Bengt", owner.getFirstName());
assertTrue("Check that Id exist: ", owner.getId() > 0);
owner.setLastName("Larsson");
ownerService.updateOwner(owner);
owner = ownerService.getOwner(owner.getId());
assertEquals("Name is changed", "Larsson", owner.getLastName());
}
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(MONTH, -3, GETDATE())
Mureinik's suggested method will return the same results, but doing it this way your query can benefit from any indexes on Date_Column
.
or you can check against last 90 days.
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(DAY, -90, GETDATE())
Here's a good post that shows how to do it.
If you want to read the values from a file other than the app.config, you need to load it into the ConfigurationManager.
Try this method: ConfigurationManager.OpenMappedExeConfiguration()
There's an example of how to use it in the MSDN article.
Just to improve Wael's answer and put it on a single line:
dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);
UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.
Normally, the VM would do a garbage collection automatically before throwing an OutOfMemoryException, so adding an explicit call shouldn't help except in that it perhaps moves the performance hit to an earlier moment in time.
However, I think I encountered a case where it might be relevant. I'm not sure though, as I have yet to test whether it has any effect:
When you memory-map a file, I believe the map() call throws an IOException when a large enough block of memory is not available. A garbage collection just before the map() file might help prevent that, I think. What do you think?
Take a Look at this Bundle for Laravel that I Made Recently !
src/googlemap.php
Pls Read the readme file first and don't forget to pass different ID if you want to have multiple Maps in one page
You have to "revert the revert". Depending on you how did the original revert, it may not be as easy as it sounds. Look at the official document on this topic.
---o---o---o---M---x---x---W---x---Y
/
---A---B-------------------C---D
to allow:
---o---o---o---M---x---x-------x-------*
/ /
---A---B-------------------C---D
But does it all work? Sure it does. You can revert a merge, and from a purely technical angle, git did it very naturally and had no real troubles.
It just considered it a change from "state before merge" to "state after merge", and that was it.
Nothing complicated, nothing odd, nothing really dangerous. Git will do it without even thinking about it.So from a technical angle, there's nothing wrong with reverting a merge, but from a workflow angle it's something that you generally should try to avoid.
If at all possible, for example, if you find a problem that got merged into the main tree, rather than revert the merge, try really hard to:
- bisect the problem down into the branch you merged, and just fix it,
- or try to revert the individual commit that caused it.
Yes, it's more complex, and no, it's not always going to work (sometimes the answer is: "oops, I really shouldn't have merged it, because it wasn't ready yet, and I really need to undo all of the merge"). So then you really should revert the merge, but when you want to re-do the merge, you now need to do it by reverting the revert.
Easisest solution:
Close any open projects.
Xcode > Preferences > Font & Colors
Make sure to press CMD+A to select all possible text types. Then change the font size from the picker.
Just use the JSON.stringify method and pass it through as the "data" parameter for the $.ajax function, like follows:
$.ajax({
type: "POST",
url: "index.php",
dataType: "json",
data: JSON.stringify({ paramName: info }),
success: function(msg){
$('.answer').html(msg);
}
});
You just need to make sure you include the JSON2.js file in your page...
It depends on what you need the value for. You (and everyone else so far) omitted the third alternative:
static const int var = 5;
#define var 5
enum { var = 5 };
Ignoring issues about the choice of name, then:
So, in most contexts, prefer the 'enum' over the alternatives. Otherwise, the first and last bullet points are likely to be the controlling factors — and you have to think harder if you need to satisfy both at once.
If you were asking about C++, then you'd use option (1) — the static const — every time.
To get the current time in milliseconds (since the epoch), use System.currentTimeMillis()
.
The easy way, try uname()
If that does not work, use gethostname() then gethostbyname() and finally gethostbyaddr()
The h_name of hostent{} should be your FQDN
Using Html Agility Pack as suggested by SLaks, this becomes very easy:
string html = webClient.DownloadString(url);
var doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNode specificNode = doc.GetElementById("nodeId");
HtmlNodeCollection nodesMatchingXPath = doc.DocumentNode.SelectNodes("x/path/nodes");
I changed color programmatically in this way :
var builder = new AlertDialog.Builder (this);
...
...
...
var dialog = builder.Show ();
int textColorId = Resources.GetIdentifier ("alertTitle", "id", "android");
TextView textColor = dialog.FindViewById<TextView> (textColorId);
textColor?.SetTextColor (Color.DarkRed);
as alertTitle, you can change other data by this way (next example is for titleDivider):
int titleDividerId = Resources.GetIdentifier ("titleDivider", "id", "android");
View titleDivider = dialog.FindViewById (titleDividerId);
titleDivider?.SetBackgroundColor (Color.Red);
this is in C#, but in java it is the same.
To get the top five most common names:
dataframe['name'].value_counts().head()
I'm recommended use MySQL Workbench where is import data. Workbench allows the user to create a new table from a file in CSV or JSON format. It handles table schema and data import in just a few clicks through the wizard.
In MySQL Workbench, use the context menu on table list and click Table Data Import Wizard
.
More from the MySQL Workbench 6.5.1 Table Data Export and Import Wizard documentation. Download MySQL Workbench here.
Not the most elegant solution, and only works 90% of the time:
def vardict(*args):
ns = inspect.stack()[1][0].f_locals
retval = {}
for a in args:
found = False
for k, v in ns.items():
if a is v:
retval[k] = v
if found:
raise ValueError("Value found in more than one local variable: " + str(a))
found = True
if found:
continue
if 'self' in ns:
for k, v in ns['self'].__dict__.items():
if a is v:
retval[k] = v
if found:
raise ValueError("Value found in more than one instance attribute: " + str(a))
found = True
if found:
continue
for k, v in globals().items():
if a is v:
retval[k] = v
if found:
raise ValueError("Value found in more than one global variable: " + str(a))
found = True
assert found, "Couldn't find one of the parameters."
return retval
You'll run into problems if you store the same reference in multiple variables, but also if multiple variables store the same small int, since these get interned.
add your service to providers[] array in app.module.ts file. Like below
// here my service is CarService
app.module.ts
import {CarsService} from './cars.service';
providers: [CarsService] // you can include as many services you have
In order to build an AJAX webservice, you need TWO files :
So, first you call your webservice using this JQuery syntax, in the JavaScript file :
$.ajax({
url : 'mywebservice.php',
type : 'POST',
data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
dataType : 'json',
success: function (data) {
alert("The file is "+data.fichierZIP);
},
error: function(data) {
//console.log(data);
var responseText=JSON.parse(data.responseText);
alert("Error(s) while building the ZIP file:\n"+responseText.messages);
}
});
Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:
<?php
//...
//I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
//$errors is a string that may contain an error message while preparing the ZIP file
//In the end, I check if there has been an error, and if so, I return an error object
//...
if ($errors==''){
//if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['ZIPFILENAME'] = basename($filename);
print json_encode($result);
} else {
//if there is an error, you should return a special header, followed by another JSON object
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['messages'] = $errors;
//feel free to add other information like $result['errorcode']
die(json_encode($result));
}
?>
From Java How to Program about abstract classes:
Because they’re used only as superclasses in inheritance hierarchies, we refer to them as abstract superclasses. These classes cannot be used to instantiate objects, because abstract classes are incomplete. Subclasses must declare the “missing pieces” to become “concrete” classes, from which you can instantiate objects. Otherwise, these subclasses, too, will be abstract.
To answer your question "What is the reason to use interfaces?":
An abstract class’s purpose is to provide an appropriate superclass from which other classes can inherit and thus share a common design.
As opposed to an interface:
An interface describes a set of methods that can be called on an object, but does not provide concrete implementations for all the methods... Once a class implements an interface, all objects of that class have an is-a relationship with the interface type, and all objects of the class are guaranteed to provide the functionality described by the interface. This is true of all subclasses of that class as well.
So, to answer your question "I was wondering when I should use interfaces", I think you should use interfaces when you want a full implementation and use abstract classes when you want partial pieces for your design (for reusability)
In your test code your are trying to pass App
to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:
1) Where the click handler calls a function passed as a prop, e.g.
class App extends Component {
myClickFunc = () => {
console.log('clickity clickcty');
this.props.someCallback();
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now pass in a spy function as a prop to the component, and assert that it is called:
describe('my sweet test', () => {
it('clicks it', () => {
const spy = jest.fn();
const app = shallow(<App someCallback={spy} />)
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
2) Where the click handler sets some state on the component, e.g.
class App extends Component {
state = {
aProperty: 'first'
}
myClickFunc = () => {
console.log('clickity clickcty');
this.setState({
aProperty: 'second'
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now make assertions about the state of the component, i.e.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const p = app.find('.App-intro')
p.simulate('click')
expect(app.state('aProperty')).toEqual('second');
})
})
With Visual Studio 2017 I had to add this folder to my Windows 10 path env variable:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.10.25017\bin\HostX64\x64
There's also HostX86
list.pop()
removes and returns the last element of the list.
For all that you add xmlbeans-2.3.0.jar and it is not working,you must use HSSFWorkbook instead of XSSFWorkbook after add jar.For instance;
Workbook workbook = new HSSFWorkbook();
Sheet listSheet = workbook.createSheet("Kisi Listesi");
int rowIndex = 0;
for (KayitParam kp : kayitList) {
Row row = listSheet.createRow(rowIndex++);
int cellIndex = 0;
row.createCell(cellIndex++).setCellValue(kp.getAd());
row.createCell(cellIndex++).setCellValue(kp.getSoyad());
row.createCell(cellIndex++).setCellValue(kp.getEposta());
row.createCell(cellIndex++).setCellValue(kp.getCinsiyet());
row.createCell(cellIndex++).setCellValue(kp.getDogumtarihi());
row.createCell(cellIndex++).setCellValue(kp.getTahsil());
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write(baos);
AMedia amedia = new AMedia("Kisiler.xls", "xls",
"application/file", baos.toByteArray());
Filedownload.save(amedia);
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
[id] [int] IDENTITY(1,1) NOT NULL,
of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.
Put them into a list
and use merge
with Reduce
Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
# id v1 v2 v3
# 1 1 1 NA NA
# 2 10 4 NA NA
# 3 2 3 4 NA
# 4 43 5 NA NA
# 5 73 2 NA NA
# 6 23 NA 2 1
# 7 57 NA 3 NA
# 8 62 NA 5 2
# 9 7 NA 1 NA
# 10 96 NA 6 NA
You can also use this more concise version:
Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))
Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.
Here is an example :
function delsheets(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
for (pa=numbofsheet-1;pa>0;--pa){
ss.setActiveSheet(ss.getSheets()[pa]);
var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
Utilities.sleep(200);// pause in the loop for 200 milliseconds
}
ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function)
}
For a div-Element you could just set the opacity via a class to enable or disable the effect.
.mute-all {
opacity: 0.4;
}
How about this :
// Checks to see if the value passed is valid.
if (!TypeDescriptor.GetConverter(typeof(T)).IsValid(value))
{
throw new ArgumentException();
}
This should do the job, no?
<Button Content="Test">
<Button.Background>
<ImageBrush ImageSource="folder/file.PNG"/>
</Button.Background>
</Button>
Try this in your css:
#ntext{
color: #000000;
}
Then the following in all your navigation bar list codes:
<li><a href="#" id="ntext"><span class="glyphicon glyphicon-user"></span> About</a></li>
When creating a file, use slashes to specify the directory. For example:
Name the file:
repositoryname/newfoldername/filename
GitHub will automatically create a folder with the name newfoldername.
With using pathlib module, indentation isn't needed.
import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))
As of python 3.6, f-strings is available.
pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")
JavaScript uses the \ (backslash) as an escape characters for:
Note that the \v and \0 escapes are not allowed in JSON strings.
In PHP5, you should use the Document Object Model class instead. Example:
$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);
$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);
$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);
echo htmlentities($domDoc->saveXML());
If you have Mac OS X, go to the file root or the folder of your website.
Then right-hand click on it, go to get information, go to the very bottom (Sharing & Permissions), open that, change all read-only to read and write. Make sure to open padlock, go to setting icon, and choose Apply to the enclosed items...
using spring boot 2.*, i have a controller that maps to routes GetMapping({"/{var}", "/{var1}/{var2}", "/{var1}/{var2}/{var3}"})
and boom my app stop serving resources.
i know it is not advisable to have such routes but it all depends on the app you are building (in my case, i have no choice but to have such routes)
so here is my hack to make sure my app serve resources again. I simply have a controller that maps to my resources. since spring will match a direct route first before any that has variable, i decided to add a controller method that maps to /imgaes/{name}
and repeated same for other resources
@GetMapping(value = "/images/{image}", produces = {MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE})
public @ResponseBody
byte[] getImage(@PathVariable String image) {
ClassPathResource file = new ClassPathResource("static/images/" + image);
byte[] bytes;
try {
bytes = StreamUtils.copyToByteArray(file.getInputStream());
} catch (IOException e) {
throw new ResourceNotFoundException("file not found: " + image);
}
return bytes;
}
and this solved my issue
You can use Visual Studio 2012.
Simply update your NuGet package in Visual Studio to Microsoft.AspNet.Mvc 5.0
.
You may have to search pre-release.
Also the default project comes with Entity Framework 6.0, and ASP.NET Razor 3.0.
You may also need ASP.NET Identity Core and OWIN.
All of these can be downloaded/updated through menu Tools ? Library package manager ? Manage NuGet Packages for Solution....
If you don't yet have NuGet, follow this tutorial:
Current Solution
Create the folder project/app/src/main/jniLibs
, and then put your *.so
files within their abi folders in that location. E.g.,
project/
+--libs/
| +-- *.jar <-- if your library has jar files, they go here
+--src/
+-- main/
+-- AndroidManifest.xml
+-- java/
+-- jniLibs/
+-- arm64-v8a/ <-- ARM 64bit
¦ +-- yourlib.so
+-- armeabi-v7a/ <-- ARM 32bit
¦ +-- yourlib.so
+-- x86/ <-- Intel 32bit
+-- yourlib.so
Deprecated solution
Add both code snippets in your module gradle.build file as a dependency:
compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
How to create this custom jar:
task nativeLibsToJar(type: Jar, description: 'create a jar archive of the native libs') {
destinationDir file("$buildDir/native-libs")
baseName 'native-libs'
from fileTree(dir: 'libs', include: '**/*.so')
into 'lib/'
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn(nativeLibsToJar)
}
Same answer can also be found in related question: Include .so library in apk in android studio
Make sure you import UIKit
let appDelegate = UIApplication.sharedApplication().delegate! as! AppDelegate
try this:
function grab_image($url,$saveto){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
if(file_exists($saveto)){
unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
and ensure that in php.ini allow_url_fopen is enable
Also you can setup extJs writer
with encode
: true
and it will send data regularly (and, hence, you will be able to retrieve data via $_POST
and $_GET
).
... the values will be sent as part of the request parameters as opposed to a raw post (via docs for encode config of Ext.data.writer.Json)
UPDATE
Also docs say that:
The encode option should only be set to true when a root is defined
So, probably, writer
's root
config is required.
import org.springframework.core.io.ClassPathResource;
...
File folder = new ClassPathResource("sql").getFile();
File[] listOfFiles = folder.listFiles();
It is worth noting that this will limit your deployment options, ClassPathResource.getFile()
only works if the container has exploded (unzipped) your war file.
I faced the same issue and tried various solutions to load the html page from Spring MVC, following solution worked for me
Step-1 in server's web.xml comment these two lines
<!-- <mime-mapping>
<extension>htm</extension>
<mime-type>text/html</mime-type>
</mime-mapping>-->
<!-- <mime-mapping>
<extension>html</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
-->
Step-2 enter following code in application's web xml
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
Step-3 create a static controller class
@Controller
public class FrontController {
@RequestMapping("/landingPage")
public String getIndexPage() {
return "CompanyInfo";
}
}
Step-4 in the Spring configuration file change the suffix to .htm .htm
Step-5 Rename page as .htm file and store it in WEB-INF and build/start the server
localhost:8080/.../landingPage
"ABABAB".replace(/B/g, "A");
As always: don't use regex unless you have to. For a simple string replace, the idiom is:
'ABABAB'.split('B').join('A')
Then you don't have to worry about the quoting issues mentioned in Gracenotes's answer.
Consider thttpd. It can run under windows.
Quoting wikipedia:
"it is uniquely suited to service high volume requests for static data"
A version of thttpd-2.25b compiled under cygwin with cygwin dll's is available. It is single threaded and particularly good for servicing images.
I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.
class FooReader {
public:
/** Constructor */
FooReader() : d(new FooReaderPrivate(this)) { } // will not compile here
.......
private:
FooReaderPrivate* d;
};
====== In a separate file =====
class FooReaderPrivate {
public:
FooReaderPrivate(FooReader*) : parent(p) { }
private:
FooReader* parent;
};
The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.
In my case, I tried everything above, nothing worked. I am pretty sure, my database looks like below.
mysql Ver 14.14 Distrib 5.7.17, for Linux (x86_64) using EditLine wrapper
Connection id: 12
Current database: xxx
Current user: yo@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server version: 5.7.17-0ubuntu0.16.04.1 (Ubuntu)
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: utf8
Db characterset: utf8
Client characterset: utf8
Conn. characterset: utf8
UNIX socket: /var/run/mysqld/mysqld.sock
Uptime: 42 min 49 sec
Threads: 1 Questions: 372 Slow queries: 0 Opens: 166 Flush tables: 1 Open tables: 30 Queries per second avg: 0.144
so, I look up the column charset in every table
show create table company;
It turns out the column charset is latin. That's why, I can not insert Chinese into database.
ALTER TABLE company CONVERT TO CHARACTER SET utf8;
That might help you. :)
If I remember from your previous questions, you're binding to a DataTable. Try this:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable sourceData = (DataTable)GridView1.DataSource;
sourceData.Rows[e.RowIndex].Delete();
GridVie1.DataSource = sourceData;
GridView1.DataBind();
}
Essentially, as I said in my comment, grab a copy of the GridView's DataSource, remove the row from it, then set the DataSource to the updated object and call DataBind() on it again.
PyFilesystem with its sshfs is one option. It uses Paramiko under the hood and provides a nicer paltform independent interface on top.
import fs
sf = fs.open_fs("sftp://[user[:password]@]host[:port]/[directory]")
sf.makedir('my_dir')
or
from fs.sshfs import SSHFS
sf = SSHFS(...
My solution was to insert <packaging>pom</packaging>
between artifactId
and version
<groupId>com.onlinechat</groupId>
<artifactId>chat-online</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>server</module>
<module>client</module>
<module>network</module>
</modules>
A very important distinction, which is easy to miss, is the default bheavior of these two functions, when it comes to exceptions.
I'll use this example to simulate a coroutine that will raise exceptions, sometimes -
import asyncio
import random
async def a_flaky_tsk(i):
await asyncio.sleep(i) # bit of fuzz to simulate a real-world example
if i % 2 == 0:
print(i, "ok")
else:
print(i, "crashed!")
raise ValueError
coros = [a_flaky_tsk(i) for i in range(10)]
await asyncio.gather(*coros)
outputs -
0 ok
1 crashed!
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 20, in <module>
asyncio.run(main())
File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/Users/dev/PycharmProjects/trading/xxx.py", line 17, in main
await asyncio.gather(*coros)
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
As you can see, the coros after index 1
never got to execute.
But await asyncio.wait(coros)
continues to execute tasks, even if some of them fail -
0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
Task exception was never retrieved
future: <Task finished name='Task-10' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Ofcourse, this behavior can be changed for both by using -
asyncio.gather(..., return_exceptions=True)
or,
asyncio.wait([...], return_when=asyncio.FIRST_EXCEPTION)
But it doesn't end here!
Notice:
Task exception was never retrieved
in the logs above.
asyncio.wait()
won't re-raise exceptions from the child tasks until you await
them individually. (The stacktrace in the logs are just messages, they cannot be caught!)
done, pending = await asyncio.wait(coros)
for tsk in done:
try:
await tsk
except Exception as e:
print("I caught:", repr(e))
Output -
0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
On the other hand, to catch exceptions with asyncio.gather()
, you must -
results = await asyncio.gather(*coros, return_exceptions=True)
for result_or_exc in results:
if isinstance(result_or_exc, Exception):
print("I caught:", repr(result_or_exc))
(Same output as before)
As long as you clearly reference the other commit from the empty commit it should be fine. Something like:
Commit message errata for [commit sha1]
[new commit message]
As others have pointed out, this is often preferable to force pushing a corrected commit.
I had the same problem just with switching the background images with reasonable sizes. I got better results with setting the ImageView to null before putting in a new picture.
ImageView ivBg = (ImageView) findViewById(R.id.main_backgroundImage);
ivBg.setImageDrawable(null);
ivBg.setImageDrawable(getResources().getDrawable(R.drawable.new_picture));
I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT
function on the nvarchar field.
Example: Left(Field,4)
Basically, the query will look like:
Select convert(float,left(Field,4)) from TABLE
Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.
Use following snippet in your code
Intent newIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.google.co.in/?gws_rd=cr"));
startActivity(newIntent);
Use This link
http://developer.android.com/reference/android/content/Intent.html#ACTION_VIEW
Okay, hopefully this should help resolve any (sane) assembly reference discrepancies ...
Rejoice.
Inspired by writing this answer, I ended up later expanding and writing a blog post going over this in careful detail. I recommend checking that out if you want to develop a deeper understanding of how to think about this problem--I try to explain it piece by piece, and also give a JSperf comparison at the end, going over speed considerations.
That said, The tl;dr is this:
To accomplish what you're asking for (filtering and mapping within one function call), you would use Array.reduce()
.
However, the more readable and (less importantly) usually significantly faster2 approach is to just use filter and map chained together:
[1,2,3].filter(num => num > 2).map(num => num * 2)
What follows is a description of how Array.reduce()
works, and how it can be used to accomplish filter and map in one iteration. Again, if this is too condensed, I highly recommend seeing the blog post linked above, which is a much more friendly intro with clear examples and progression.
You give reduce an argument that is a (usually anonymous) function.
That anonymous function takes two parameters--one (like the anonymous functions passed in to map/filter/forEach) is the iteratee to be operated on. There is another argument for the anonymous function passed to reduce, however, that those functions do not accept, and that is the value that will be passed along between function calls, often referred to as the memo.
Note that while Array.filter() takes only one argument (a function), Array.reduce() also takes an important (though optional) second argument: an initial value for 'memo' that will be passed into that anonymous function as its first argument, and subsequently can be mutated and passed along between function calls. (If it is not supplied, then 'memo' in the first anonymous function call will by default be the first iteratee, and the 'iteratee' argument will actually be the second value in the array)
In our case, we'll pass in an empty array to start, and then choose whether to inject our iteratee into our array or not based on our function--this is the filtering process.
Finally, we'll return our 'array in progress' on each anonymous function call, and reduce will take that return value and pass it as an argument (called memo) to its next function call.
This allows filter and map to happen in one iteration, cutting down our number of required iterations in half--just doing twice as much work each iteration, though, so nothing is really saved other than function calls, which are not so expensive in javascript.
For a more complete explanation, refer to MDN docs (or to my post referenced at the beginning of this answer).
Basic example of a Reduce call:
let array = [1,2,3];
const initialMemo = [];
array = array.reduce((memo, iteratee) => {
// if condition is our filter
if (iteratee > 1) {
// what happens inside the filter is the map
memo.push(iteratee * 2);
}
// this return value will be passed in as the 'memo' argument
// to the next call of this function, and this function will have
// every element passed into it at some point.
return memo;
}, initialMemo)
console.log(array) // [4,6], equivalent to [(2 * 2), (3 * 2)]
more succinct version:
[1,2,3].reduce((memo, value) => value > 1 ? memo.concat(value * 2) : memo, [])
Notice that the first iteratee was not greater than one, and so was filtered. Also note the initialMemo, named just to make its existence clear and draw attention to it. Once again, it is passed in as 'memo' to the first anonymous function call, and then the returned value of the anonymous function is passed in as the 'memo' argument to the next function.
Another example of the classic use case for memo would be returning the smallest or largest number in an array. Example:
[7,4,1,99,57,2,1,100].reduce((memo, val) => memo > val ? memo : val)
// ^this would return the largest number in the list.
An example of how to write your own reduce function (this often helps understanding functions like these, I find):
test_arr = [];
// we accept an anonymous function, and an optional 'initial memo' value.
test_arr.my_reducer = function(reduceFunc, initialMemo) {
// if we did not pass in a second argument, then our first memo value
// will be whatever is in index zero. (Otherwise, it will
// be that second argument.)
const initialMemoIsIndexZero = arguments.length < 2;
// here we use that logic to set the memo value accordingly.
let memo = initialMemoIsIndexZero ? this[0] : initialMemo;
// here we use that same boolean to decide whether the first
// value we pass in as iteratee is either the first or second
// element
const initialIteratee = initialMemoIsIndexZero ? 1 : 0;
for (var i = initialIteratee; i < this.length; i++) {
// memo is either the argument passed in above, or the
// first item in the list. initialIteratee is either the
// first item in the list, or the second item in the list.
memo = reduceFunc(memo, this[i]);
// or, more technically complete, give access to base array
// and index to the reducer as well:
// memo = reduceFunc(memo, this[i], i, this);
}
// after we've compressed the array into a single value,
// we return it.
return memo;
}
The real implementation allows access to things like the index, for example, but I hope this helps you get an uncomplicated feel for the gist of it.
Here's an example of creating and using an event with C#
using System;
namespace Event_Example
{
//First we have to define a delegate that acts as a signature for the
//function that is ultimately called when the event is triggered.
//You will notice that the second parameter is of MyEventArgs type.
//This object will contain information about the triggered event.
public delegate void MyEventHandler(object source, MyEventArgs e);
//This is a class which describes the event to the class that recieves it.
//An EventArgs class must always derive from System.EventArgs.
public class MyEventArgs : EventArgs
{
private string EventInfo;
public MyEventArgs(string Text)
{
EventInfo = Text;
}
public string GetInfo()
{
return EventInfo;
}
}
//This next class is the one which contains an event and triggers it
//once an action is performed. For example, lets trigger this event
//once a variable is incremented over a particular value. Notice the
//event uses the MyEventHandler delegate to create a signature
//for the called function.
public class MyClass
{
public event MyEventHandler OnMaximum;
private int i;
private int Maximum = 10;
public int MyValue
{
get
{
return i;
}
set
{
if(value <= Maximum)
{
i = value;
}
else
{
//To make sure we only trigger the event if a handler is present
//we check the event to make sure it's not null.
if(OnMaximum != null)
{
OnMaximum(this, new MyEventArgs("You've entered " +
value.ToString() +
", but the maximum is " +
Maximum.ToString()));
}
}
}
}
}
class Program
{
//This is the actual method that will be assigned to the event handler
//within the above class. This is where we perform an action once the
//event has been triggered.
static void MaximumReached(object source, MyEventArgs e)
{
Console.WriteLine(e.GetInfo());
}
static void Main(string[] args)
{
//Now lets test the event contained in the above class.
MyClass MyObject = new MyClass();
MyObject.OnMaximum += new MyEventHandler(MaximumReached);
for(int x = 0; x <= 15; x++)
{
MyObject.MyValue = x;
}
Console.ReadLine();
}
}
}
I am not aware of any solution for the second part of your question. The reason is that it is not clear how to define I changed. Changed when? Just between 2 saves or between commits... Basically - forget it.
I assume you would like to stick to some guideline, but do not touch the rest of the code. But the guideline should be used overall, and not for bites and pieces. So my suggestion is - change all the code to the guideline: it is once-off operation, but make sure that all your developers have the same plugin (AnyEdit) with the same settings for the project.
It's even easier to do without a library
window.onload = function() {
// code
};
String x = JComboBox.getSelectedItem().toString();
will convert any value weather it is Integer, Double, Long, Short into text on the other hand,
String x = String.valueOf(JComboBox.getSelectedItem());
will avoid null values, and convert the selected item from object to string
From GNU Make error appendix, as you see this is not a Make error but an error coming from gcc.
‘[foo] Error NN’ ‘[foo] signal description’ These errors are not really make errors at all. They mean that a program that make invoked as part of a recipe returned a non-0 error code (‘Error NN’), which make interprets as failure, or it exited in some other abnormal fashion (with a signal of some type). See Errors in Recipes. If no *** is attached to the message, then the subprocess failed but the rule in the makefile was prefixed with the - special character, so make ignored the error.
So in order to attack the problem, the error message from gcc is required. Paste the command in the Makefile directly to the command line and see what gcc says. For more details on Make errors click here.
You can keymap ctrl+s
to save AND compile in one step. Go to the keymap settings and search for Compile
.
break
is used when you want to exit from the loop, while return
is used to go back to the step where it was called or to stop further execution.
You can cast it to an intptr_t
type. It's an int
type guaranteed to be big enough to contain a pointer. Use #include <cstdint>
to define it.
To Encrypt:
$ openssl bf < arquivo.txt > arquivo.txt.bf
To Decrypt:
$ openssl bf -d < arquivo.txt.bf > arquivo.txt
bf === Blowfish in CBC mode
<div class="headerdivider"></div>
and
.headerdivider {
border-left: 1px solid #38546d;
background: #16222c;
width: 1px;
height: 80px;
position: absolute;
right: 250px;
top: 10px;
}
If you can change the input type, I think this solution would be much easier:
You can simple use type="url"
in your input and the check it with checkValidity()
in js
E.g:
your.html
<input id="foo" type="url">
your.js
// The selector is JQuery, but the function is plain JS
$("#foo").on("keyup", function() {
if (this.checkValidity()) {
// The url is valid
} else {
// The url is invalid
}
});
Have you run npm init
? That command runs you through everything...
This is what worked for me:
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
try {
keyStore.load(instream, "password".toCharArray());
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, "password".toCharArray())
//.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
CloseableHttpClient httpclient = HttpClients.custom()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
.setSSLSocketFactory(sslsf)
.build();
try {
HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
This code is a modified version of http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java
There are two problems with this code:
EDIT: The solution below is only for HTML "fragments" since html,head and body are removed. I guess the solution for this question is DOMParser's parseFromString() method.
For HTML fragments, the solutions listed here works for most HTML, however for certain cases it won't work.
For example try parsing <td>Test</td>
. This one won't work on the div.innerHTML solution nor DOMParser.prototype.parseFromString nor range.createContextualFragment solution. The td tag goes missing and only the text remains.
Only jQuery handles that case well.
So the future solution (MS Edge 13+) is to use template tag:
function parseHTML(html) {
var t = document.createElement('template');
t.innerHTML = html;
return t.content.cloneNode(true);
}
var documentFragment = parseHTML('<td>Test</td>');
For older browsers I have extracted jQuery's parseHTML() method into an independent gist - https://gist.github.com/Munawwar/6e6362dbdf77c7865a99
add these code into the top of your script to solve problem
@set_magic_quotes_runtime(false);
ini_set('magic_quotes_runtime', 0);
INSERT INTO table 2
SELECT * FROM table1/view1
http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells
CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
Really human comprehensible example (as this is the first time I am using %in%), how to compare two data frames and keep only rows containing the equal values in specific column:
# Set seed for reproducibility.
set.seed(1)
# Create two sample data frames.
data_A <- data.frame(id=c(1,2,3), value=c(1,2,3))
data_B <- data.frame(id=c(1,2,3,4), value=c(5,6,7,8))
# compare data frames by specific columns and keep only
# the rows with equal values
data_A[data_A$id %in% data_B$id,] # will keep data in data_A
data_B[data_B$id %in% data_A$id,] # will keep data in data_b
Results:
> data_A[data_A$id %in% data_B$id,]
id value
1 1 1
2 2 2
3 3 3
> data_B[data_B$id %in% data_A$id,]
id value
1 1 5
2 2 6
3 3 7
The charset is a property of the database (default) and the table. You can have a look (MySQL commands):
show create database foo;
> CREATE DATABASE `foo`.`foo` /*!40100 DEFAULT CHARACTER SET latin1 */
show create table foo.bar;
> lots of stuff ending with
> ) ENGINE=InnoDB AUTO_INCREMENT=252 DEFAULT CHARSET=latin1
In other words; it's quite easy to check your database charset or change it:
ALTER TABLE `foo`.`bar` CHARACTER SET utf8;
To redirect to another page, you can use:
window.location = "http://www.yoururl.com";
First off: a List
is a Collection
. It is a specialized Collection
, however.
A Collection
is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.
A List
adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.
In a Collection
you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.
There are other specialized Collections as well, for example a Set
which adds the feature that it will never contain the same element twice.
This is easy with a flexbox:
#wrapper {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#left {_x000D_
flex: 0 0 65%;_x000D_
}_x000D_
_x000D_
#right {_x000D_
flex: 1;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="left">Left side div</div>_x000D_
<div id="right">Right side div</div>_x000D_
</div>
_x000D_
A helpful step in tracking down this problem is to identify which bind-address MySQL is actually set to. You can do this with netstat:
netstat -nat |grep :3306
This helped me zero in on my problem, because there are multiple mysql config files, and I had edited the wrong one. Netstat showed mysql was still using the wrong config:
ubuntu@myhost:~$ netstat -nat |grep :3306
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
So I grepped the config directories for any other files which might be overriding my setting and found:
ubuntu@myhost:~$ sudo grep -R bind /etc/mysql
/etc/mysql/mysql.conf.d/mysqld.cnf:bind-address = 127.0.0.1
/etc/mysql/mysql.cnf:bind-address = 0.0.0.0
/etc/mysql/my.cnf:bind-address = 0.0.0.0
D'oh! This showed me the setting I had adjusted was the wrong config file, so I edited the RIGHT file this time, confirmed it with netstat, and was in business.
In WPF there is a control named Popup.
Popup myPopup = new Popup();
//(...)
myPopup.IsOpen = true;
Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.
npm install --save multer
in app.js
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './public/uploads');
},
filename: function (req, file, callback) {
console.log(file);
callback(null, Date.now()+'-'+file.originalname)
}
});
var upload = multer({storage: storage}).single('photo');
router.route("/storedata").post(function(req, res, next){
upload(req, res, function(err) {
if(err) {
console.log('Error Occured');
return;
}
var userDetail = new mongoOp.User({
'name':req.body.name,
'email':req.body.email,
'mobile':req.body.mobile,
'address':req.body.address
});
console.log(req.file);
res.end('Your File Uploaded');
console.log('Photo Uploaded');
userDetail.save(function(err,result){
if (err) {
return console.log(err)
}
console.log('saved to database')
})
})
res.redirect('/')
});
Try using
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
Use array array_flip
in php
$array = array ( [1] => Sell [2] => Buy [3] => Rent [4] => Jobs )
print_r(array_flip($array));
Array ( [Sell] => 1 [Buy] => 2 [Rent] => 3 [Jobs] => 4 )
SOLVED: I faced this error and i cant understand, it took 5 hours.
Solution: project properties/Project faced/Dynamic web-module version set to 3.0
after one week ,I got same error
FIXED2 gwt-project-external-mode-main-main-nocache-js-not-found
Using WebClient.UploadString
or WebClient.UploadData
you can POST data to the server easily. I’ll show an example using UploadData, since UploadString is used in the same manner as DownloadString.
byte[] bret = client.UploadData("http://www.website.com/post.php", "POST",
System.Text.Encoding.ASCII.GetBytes("field1=value1&field2=value2") );
string sret = System.Text.Encoding.ASCII.GetString(bret);
Just my 2 cents worth, if your filename contains spaces, ie "c:\My File Contains Spaces.txt", you'll need to surround the filename with quotes otherwise explorer will assume that the othe words are different arguments...
string argument = "/select, \"" + filePath +"\"";
Using Retrofit 2.0 you may use this:
@Multipart
@POST("uploadImage")
Call<ResponseBody> uploadImage(@Part("file\"; fileName=\"myFile.png\" ")RequestBody requestBodyFile, @Part("image") RequestBody requestBodyJson);
Make a request:
File imgFile = new File("YOUR IMAGE FILE PATH");
RequestBody requestBodyFile = RequestBody.create(MediaType.parse("image/*"), imgFile);
RequestBody requestBodyJson = RequestBody.create(MediaType.parse("text/plain"),
retrofitClient.getJsonObject(uploadRequest));
//make sync call
Call<ResponseBody> uploadBundle = uploadImpl.uploadImage(requestBodyFile, requestBodyJson);
Response<BaseResponse> response = uploadBundle.execute();
please refer https://square.github.io/retrofit/
This worked for me:
hoja_trabajo.Cells[i + 2, j + 1] = fecha.ToString("dd-MMM-yyyy").Replace(".", "");
Here is a plain and simple explanation:
// Include the public functions from 'helpers.js'
var helpers = require('./helpers');
// Let's assume this is the data which comes from the database or somewhere else
var databaseName = 'Walter';
var databaseSurname = 'Heisenberg';
// Use the function from 'helpers.js' in the main file, which is server.js
var fullname = helpers.concatenateNames(databaseName, databaseSurname);
// 'module.exports' is a node.JS specific feature, it does not work with regular JavaScript
module.exports =
{
// This is the function which will be called in the main file, which is server.js
// The parameters 'name' and 'surname' will be provided inside the function
// when the function is called in the main file.
// Example: concatenameNames('John,'Doe');
concatenateNames: function (name, surname)
{
var wholeName = name + " " + surname;
return wholeName;
},
sampleFunctionTwo: function ()
{
}
};
// Private variables and functions which will not be accessible outside this file
var privateFunction = function ()
{
};
Using your code you can do something like this in plain JavaScript using the cloneNode() method:
// Create a clone of element with id ddl_1:
let clone = document.querySelector('#ddl_1').cloneNode( true );
// Change the id attribute of the newly created element:
clone.setAttribute( 'id', newId );
// Append the newly created element on element p
document.querySelector('p').appendChild( clone );
Or using jQuery clone() method (not the most efficient):
$('#ddl_1').clone().attr('id', newId).appendTo('p'); // append to where you want
SELECT {FN LENGTH('123-345-566')} - {FN LENGTH({FN REPLACE('123-345-566', '#', '')})} FROM DUAL
In Python, creating a new object is often better than modifying an existing one:
item_list = ['item', 5, 'foo', 3.14, True]
item_list = [e for e in item_list if e not in ('item', 5)]
Which is equivalent to:
item_list = ['item', 5, 'foo', 3.14, True]
new_list = []
for e in item_list:
if e not in ('item', 5):
new_list.append(e)
item_list = new_list
In case of a big list of filtered out values (here, ('item', 5)
is a small set of elements), using a set
is faster as the in
operation is O(1) time complexity on average. It's also a good idea to build the iterable you're removing first, so that you're not creating it on every iteration of the list comprehension:
unwanted = {'item', 5}
item_list = [e for e in item_list if e not in unwanted]
A bloom filter is also a good solution if memory is not cheap.
I use an Android Studio plug-in called "adb idea" -- has a drop down menu for various functions (Uninstall, Kill, Start, etc) that you can target at any connected or simulated device. One could argue it takes me a step away from having a deeper understanding of the power of adb commands and I'd probably agree....though I'm really operating at a lower level of understanding anyway so for me it helps to have a helper. ADB Idea
/** length should be less than 4 (for int) **/
public long byteToInt(byte[] bytes, int length) {
int val = 0;
if(length>4) throw new RuntimeException("Too big to fit in int");
for (int i = 0; i < length; i++) {
val=val<<8;
val=val|(bytes[i] & 0xFF);
}
return val;
}
you can do it with Procedure also so i have a procedure for this
DELIMITER $$
CREATE PROCEDURE copyTo()
BEGIN
DECLARE x INT;
DECLARE str varchar(45);
SET x = 1;
set str = '';
WHILE x < 5 DO
set str = (select source_col from emp where id=x);
update emp set target_col =str where id=x;
SET x = x + 1;
END WHILE;
END$$
DELIMITER ;
None of these answers mention the colClasses
argument which is another way to specify the variable classes in read.csv
.
stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "numeric") # all variables to numeric
or you can specify which columns to convert:
stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = c("PTS" = "numeric", "MP" = "numeric") # specific columns to numeric
Note that if a variable can't be converted to numeric then it will be converted to factor as default which makes it more difficult to convert to number. Therefore, it can be advisable just to read all variables in as 'character' colClasses = "character"
and then convert the specific columns to numeric once the csv is read in:
stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "character")
point <- as.numeric(stuckey$PTS)
time <- as.numeric(stuckey$MP)
if you open localhost/phpmyadmin
you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.
Arrays are, in general, a poor data structure to use if you want to ask if a particular object is in the collection or not.
If you'll be running this search frequently, it might be worth it to use a Dictionary<string, something>
rather than an array. Lookups in a Dictionary are O(1) (constant-time), while searching through the array is O(N) (takes time proportional to the length of the array).
Even if the array is only 200 items at most, if you do a lot of these searches, the Dictionary will likely be faster.
It would involve the cURL PHP extension.
$ch = curl_init('http://www.provider.com/process.jsp');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "id=12345&name=John");
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1); // RETURN THE CONTENTS OF THE CALL
$resp = curl_exec($ch);
git bundle
I like that method, as it results in only one file, easier to copy around.
See ProGit: little bundle of joy.
See also "How can I email someone a git repository?", where the command
git bundle create /tmp/foo-all --all
is detailed:
git bundle
will only package references that are shown by git show-ref: this includes heads, tags, and remote heads.
It is very important that the basis used be held by the destination.
It is okay to err on the side of caution, causing the bundle file to contain objects already in the destination, as these are ignored when unpacking at the destination.
For using that bundle, you can clone it, specifying a non-existent folder (outside of any git repo):
git clone /tmp/foo-all newFolder
Our HTML:
<div id="addnew">
<input type="text" id="id">
<input type="text" id="content">
<input type="button" value="Add" id="submit">
</div>
<div id="check">
<input type="text" id="input">
<input type="button" value="Search" id="search">
</div>
JS (writing to the txt file):
function writeToFile(d1, d2){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
var id = document.getElementById("id").value;
var content = document.getElementById("content").value;
writeToFile(id, content);
}
checking a particular row:
function readFile(){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 1, false, 0);
var lines = "";
while (!fh.AtEndOfStream) {
lines += fh.ReadLine() + "\r";
}
fh.Close();
return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
var input = document.getElementById("input").value;
if (input != "") {
var text = readFile();
var lines = text.split("\r");
lines.pop();
var result;
for (var i = 0; i < lines.length; i++) {
if (lines[i].match(new RegExp(input))) {
result = "Found: " + lines[i].split(",")[1];
}
}
if (result) { alert(result); }
else { alert(input + " not found!"); }
}
}
Put these inside a .hta
file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.
Try Stretch="UniformToFill" on the Image
The clear
property indicates that the left, right or both sides of an element can not be adjacent to earlier floated elements within the same block formatting context. Cleared elements are pushed below the corresponding floated elements. Examples:
clear: none;
Element remains adjacent to floated elementsbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
float: right;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.clear-none {_x000D_
clear: none;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-none">clear: none;</div>
_x000D_
clear: left;
Element pushed below left floated elementsbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
float: right;_x000D_
width: 60px;_x000D_
height: 120px;_x000D_
background: #CEF;_x000D_
}_x000D_
.clear-left {_x000D_
clear: left;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-left">clear: left;</div>
_x000D_
clear: right;
Element pushed below right floated elementsbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 120px;_x000D_
background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
float: right;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.clear-right {_x000D_
clear: right;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-right">clear: right;</div>
_x000D_
clear: both;
Element pushed below all floated elementsbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
float: right;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.clear-both {_x000D_
clear: both;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-both">clear: both;</div>
_x000D_
clear
does not affect floats outside the current block formatting contextbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 120px;_x000D_
background: #CEF;_x000D_
}_x000D_
.inline-block {_x000D_
display: inline-block;_x000D_
background: #BDF;_x000D_
}_x000D_
.inline-block .float-left {_x000D_
height: 60px;_x000D_
}_x000D_
.clear-both {_x000D_
clear: both;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="inline-block">_x000D_
<div>display: inline-block;</div>_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="clear-both">clear: both;</div>_x000D_
</div>
_x000D_
Having used many of these solutions, I find using the trick of setting border-color: transparent
to be the most flexible and widely-supported:
.some-element {
border: solid 1px transparent;
}
.some-element-selected {
border: solid 1px black;
}
Why it's better:
outline
, you can still specify, e.g., top and bottom borders separatelySimply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
A neat trick for fast rounding is to add .5 before you cast your decimal to an int.
decimal d = 10.1m;
d += .5m;
int i = (int)d;
Still leaves i=10
, but
decimal d = 10.5m;
d += .5m;
int i = (int)d;
Would round up so that i=11
.
Suppose your "Don't Check" list is on Sheet2 in cells A1:A100
, say, and your current client IDs are in Sheet1 in Column A.
What you would do is:
Conditional Formatting
> New Rule
> Use a Formula to determine which cells to format
=ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0))
and select how you want those rows formattedAnd that should do the trick.
( found here) :
var lunch = {
sandwich: 'ham',
age: 48,
};
lunch.forEach2(function (item, key) {
console.log(key);
console.log(item);
});
Code:
if (!Object.prototype.forEach2) {
Object.defineProperty(Object.prototype, 'forEach2', {
value: function (callback, thisArg) {
if (this == null) {
throw new TypeError('Not an object');
}
thisArg = thisArg || window;
for (var key in this) {
if (this.hasOwnProperty(key)) {
callback.call(thisArg, this[key], key, this);
}
}
}
});
}
open a website https://adviserinfo.sec.gov/compilation and click on button to download the file and even i want to close the pop up if it comes using python selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.webdriver.chrome.options import Options
#For Mac - If you use windows change the chromedriver location
chrome_path = '/usr/local/bin/chromedriver'
driver = webdriver.Chrome(chrome_path)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-popup-blocking")
driver.maximize_window()
driver.get("https://adviserinfo.sec.gov/compilation")
# driver.get("https://adviserinfo.sec.gov/")
# tabName = driver.find_element_by_link_text("Investment Adviser Data")
# tabName.click()
time.sleep(3)
# report1 = driver.find_element_by_xpath("//div[@class='compilation-container ng-scope layout-column flex']//div[1]//div[1]//div[1]//div[2]//button[1]")
report1 = driver.find_element_by_xpath("//button[@analytics-label='IAPD - SEC Investment Adviser Report (GZIP)']")
# print(report1)
report1.click()
time.sleep(5)
driver.close()
I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.
I modified @Alisa's code and used cProfile
to show why list comprehension is faster:
from functools import reduce
import datetime
def reduce_(numbers):
return reduce(lambda sum, next: sum + next * next, numbers, 0)
def for_loop(numbers):
a = []
for i in numbers:
a.append(i*2)
a = sum(a)
return a
def map_(numbers):
sqrt = lambda x: x*x
return sum(map(sqrt, numbers))
def list_comp(numbers):
return(sum([i*i for i in numbers]))
funcs = [
reduce_,
for_loop,
map_,
list_comp
]
if __name__ == "__main__":
# [1, 2, 5, 3, 1, 2, 5, 3]
import cProfile
for f in funcs:
print('=' * 25)
print("Profiling:", f.__name__)
print('=' * 25)
pr = cProfile.Profile()
for i in range(10**6):
pr.runcall(f, [1, 2, 5, 3, 1, 2, 5, 3])
pr.create_stats()
pr.print_stats()
Here's the results:
=========================
Profiling: reduce_
=========================
11000000 function calls in 1.501 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1000000 0.162 0.000 1.473 0.000 profiling.py:4(reduce_)
8000000 0.461 0.000 0.461 0.000 profiling.py:5(<lambda>)
1000000 0.850 0.000 1.311 0.000 {built-in method _functools.reduce}
1000000 0.028 0.000 0.028 0.000 {method 'disable' of '_lsprof.Profiler' objects}
=========================
Profiling: for_loop
=========================
11000000 function calls in 1.372 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1000000 0.879 0.000 1.344 0.000 profiling.py:7(for_loop)
1000000 0.145 0.000 0.145 0.000 {built-in method builtins.sum}
8000000 0.320 0.000 0.320 0.000 {method 'append' of 'list' objects}
1000000 0.027 0.000 0.027 0.000 {method 'disable' of '_lsprof.Profiler' objects}
=========================
Profiling: map_
=========================
11000000 function calls in 1.470 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1000000 0.264 0.000 1.442 0.000 profiling.py:14(map_)
8000000 0.387 0.000 0.387 0.000 profiling.py:15(<lambda>)
1000000 0.791 0.000 1.178 0.000 {built-in method builtins.sum}
1000000 0.028 0.000 0.028 0.000 {method 'disable' of '_lsprof.Profiler' objects}
=========================
Profiling: list_comp
=========================
4000000 function calls in 0.737 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1000000 0.318 0.000 0.709 0.000 profiling.py:18(list_comp)
1000000 0.261 0.000 0.261 0.000 profiling.py:19(<listcomp>)
1000000 0.131 0.000 0.131 0.000 {built-in method builtins.sum}
1000000 0.027 0.000 0.027 0.000 {method 'disable' of '_lsprof.Profiler' objects}
IMHO:
reduce
and map
are in general pretty slow. Not only that, using sum
on the iterators that map
returned is slow, compared to sum
ing a listfor_loop
uses append, which is of course slow to some extentsum
much quicker, in contrast to map
Working code for Excel Export
try
{
DataTable dt = DS.Tables[0];
string attachment = "attachment; filename=log.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dt.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
catch (Exception Ex)
{ }
A bit simplified you can think of it as arrays being a special case and not ordinary classes (a bit like primitives, but not). String and all the collections are classes, hence the methods to get size, length or similar things.
I guess the reason at the time of the design was performance. If they created it today they had probably come up with something like array-backed collection classes instead.
If anyone is interested, here is a small snippet of code to illustrate the difference between the two in generated code, first the source:
public class LengthTest {
public static void main(String[] args) {
int[] array = {12,1,4};
String string = "Hoo";
System.out.println(array.length);
System.out.println(string.length());
}
}
Cutting a way the not so important part of the byte code, running javap -c
on the class results in the following for the two last lines:
20: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
23: aload_1
24: arraylength
25: invokevirtual #4; //Method java/io/PrintStream.println:(I)V
28: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
31: aload_2
32: invokevirtual #5; //Method java/lang/String.length:()I
35: invokevirtual #4; //Method java/io/PrintStream.println:(I)V
In the first case (20-25) the code just asks the JVM for the size of the array (in JNI this would have been a call to GetArrayLength()) whereas in the String case (28-35) it needs to do a method call to get the length.
In the mid 1990s, without good JITs and stuff, it would have killed performance totally to only have the java.util.Vector (or something similar) and not a language construct which didn't really behave like a class but was fast. They could of course have masked the property as a method call and handled it in the compiler but I think it would have been even more confusing to have a method on something that isn't a real class.