List<Card> list = new ArrayList<Card>(Arrays.asList(hand));
I've an object (basically a VO) in Java and I don't know its type. I need to get values which are not null in that object.
Maybe you don't necessary need reflection for that -- here is a plain OO design that might solve your problem:
Validation
which expose a method validate
which checks the fields and return whatever is appropriate. Validation
and check that easily.I guess that you need the field that are null to display an error message in a generic way, so that should be enough. Let me know if this doesn't work for you for some reason.
in Project window right click on your project and select properties go to Run and set Main Class ( you can brows it) . this manual work if you have static main in some class :
public class Someclass
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
//your code
}
}
Netbeans doesn't have any conflict with W7 and you can use version 6.8 .
I don't think that other example is what you're looking for. If you're just updating one column from another column in the same table you should be able to use something like this.
update some_table set null_column = not_null_column where null_column is null
In my case this worked.
@Override
public void onViewRecycled(MyViewHolder holder) {
holder.checkbox.setChecked(false); // - this line do the trick
super.onViewRecycled(holder);
}
above answers In simple words,
you have to register under @NgModule
's
declarations: [
AppComponent, YourNewComponentHere
]
of app.module.ts
do not forget to import
that component.
If you want to use class, you can do this.
Helper.js
function x(){}
function y(){}
export default class Helper{
static x(){ x(); }
static y(){ y(); }
}
App.js
import Helper from 'helper.js';
/****/
Helper.x
Even though '
reads nicer than '
and it's a shame not to use it, as a fail-safe, use '
.
'
is a valid HTML 5 entity, however it is not a valid HTML 4 entity.
Unless <!DOCTYPE html>
is at the top of your HTML document, use '
In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.
Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.
I'd do it this way:
from os.path import abspath, exists
f_path = abspath("fooabar.txt")
if exists(f_path):
with open(f_path) as f:
print f.read()
The above code builds an absolute path to the file using abspath and is equivalent to using normpath(join(os.getcwd(), path))
[that's from the pydocs]. It then checks if that file actually exists and then uses a context manager to open it so you don't have to remember to call close on the file handle. IMHO, doing it this way will save you a lot of pain in the long run.
You need to find out what the variable User would look like when you just press Enter. I won't give you the full answer, but a tip: Fire an interpreter and try it out. It's not that hard ;) Notice that print's sep is '\n' by default (was that too much :o)
I would add this as a comment to haridsv's response, but I lack the reputation to do so:
Some of us are still stuck on a version of Python older than 2.6 (required for Thread.ident), so I got the code working in Python 2.5 (though without the thread name being displayed) as such:
import traceback
import sys
def dumpstacks(signal, frame):
code = []
for threadId, stack in sys._current_frames().items():
code.append("\n# Thread: %d" % (threadId))
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
print "\n".join(code)
import signal
signal.signal(signal.SIGQUIT, dumpstacks)
What you need to add is a custom HostnameVerifier
class bypasses certificate verification and returns true
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
This needs to be placed appropriately in your code.
If you are willing to use Three20 framework, it has a category on NSString that adds stringByRemovingHTMLTags method. See NSStringAdditions.h in Three20Core subproject.
It's possible to argue that using SSHs key to authenticate is less secure because we tend to change our password more periodically than we generate new SSH keys.
Servers that limit the lifespan for which they'll honor given SSH keys can help force users toward the practice of refreshing SSH-keys periodically.
File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println(file.getName());
}
}
Let me introduce you to my friend "dotglob". It turns on and off whether or not "*" includes hidden files.
$ mkdir test
$ cd test
$ touch a b c .hidden .hi .den
$ ls -a
. .. .den .hi .hidden a b c
$ shopt -u dotglob
$ ls *
a b c
$ for i in * ; do echo I found: $i ; done
I found: a
I found: b
I found: c
$ shopt -s dotglob
$ ls *
.den .hi .hidden a b c
$ for i in * ; do echo I found: $i ; done
I found: .den
I found: .hi
I found: .hidden
I found: a
I found: b
I found: c
It defaults to "off".
$ shopt dotglob
dotglob off
It is best to turn it back on when you are done otherwise you will confuse things that assume it will be off.
Resumee of Richard Fearn's answer , to make each second line gray:
jTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
return c;
}
});
Also try to update your browser because Angular need latest browser. check: https://angular.io/guide/browser-support
I fixed console.log issue after updating latest browser.
On Mac OS X, it's in the Python framework in /System/Library/Frameworks/Python.framework/Resources
.
Full path is:
/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Btw it's easy to find out where you can find a specific binary: which Python
will show you the path of your Python binary (which is probably the same as I posted above).
jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23
link Couting characters, words, lenght of the words and total lenght in a sentence
Your GetHashCode
implementation always returns the same value. Distinct
relies on a good hash function to work efficiently because it internally builds a hash table.
When implementing interfaces of classes it is important to read the documentation, to know which contract you’re supposed to implement.1
In your code, the solution is to forward GetHashCode
to Class_reglement.Numf.GetHashCode
and implement it appropriately there.
Apart from that, your Equals
method is full of unnecessary code. It could be rewritten as follows (same semantics, ¼ of the code, more readable):
public bool Equals(Class_reglement x, Class_reglement y)
{
return x.Numf == y.Numf;
}
Lastly, the ToList
call is unnecessary and time-consuming: AddRange
accepts any IEnumerable
so conversion to a List
isn’t required. AsEnumerable
is also redundant here since processing the result in AddRange
will cause this anyway.
1 Writing code without knowing what it actually does is called cargo cult programming. It’s a surprisingly widespread practice. It fundamentally doesn’t work.
What you are trying to do is add additional information to each item in the list that you already created so
alist[ 'from form', 'stuff 2', 'stuff 3']
for j in range( 0,len[alist]):
temp= []
temp.append(alist[j]) # alist[0] is 'from form'
temp.append('t') # slot for first piece of data 't'
temp.append('-') # slot for second piece of data
blist.append(temp) # will be alist with 2 additional fields for extra stuff assocated with each item in alist
in almost all cases, comments are evil: http://gooddeveloper.wordpress.com/
The default password which worked for me after immediate installation of mysql server is : mysql
Java 8
System.out.println(LocalDateTime.now().getHour()); // 7
System.out.println(LocalDateTime.now().getMinute()); // 45
System.out.println(LocalDateTime.now().getSecond()); // 32
Calendar
System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); // 7
System.out.println(Calendar.getInstance().get(Calendar.MINUTE)); // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND)); // 32
Joda Time
System.out.println(new DateTime().getHourOfDay()); // 7
System.out.println(new DateTime().getMinuteOfHour()); // 45
System.out.println(new DateTime().getSecondOfMinute()); // 32
Java 8
// 07:48:55.056
System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
// 7:48:55
System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());
// 07:48:55
System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));
// 074855
System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));
// 07:48:55
System.out.println(new Date().toString().substring(11, 20));
Simple example of batch code using %var%, !var!, and %%.
In this example code, focus here is that we want to capture a start time using the built in variable TIME (using time because it always changes automatically):
Code:
@echo off
setlocal enabledelayedexpansion
SET "SERVICES_LIST=MMS ARSM MMS2"
SET START=%TIME%
SET "LAST_SERVICE="
for %%A in (%SERVICES_LIST%) do (
SET START=!TIME!
CALL :SOME_FUNCTION %%A
SET "LAST_SERVICE=%%A"
ping -n 5 127.0.0.1 > NUL
SET OTHER=!START!
if !OTHER! EQU !START! (
echo !OTHER! is equal to !START! as expected
) ELSE (
echo NOTHING
)
)
ECHO Last service run was %LAST_SERVICE%
:: Function declared like this
:SOME_FUNCTION
echo Running: %1
EXIT /B 0
Comments on code:
Further reading
Use the following links to determine why in more detail:
var valArr = ["1","2","3"];
/* Below Code Matches current object's (i.e. option) value with the array values */
/* Returns -1 if match not found */
$("select").multiselect("widget").find(":checkbox").each(function(){
if(jQuery.inArray(this.value, valArr) !=-1)
this.click();
});
This selects the options whose value matches with values in array.
I was running into this with a ServiceStack dll I had installed with nuget. Turns out there was another set of dlls available that were labeled signed. Not going to be the answer for everyone, but you may just need to check for an existing signed version of your assembly.
Just think of it as the "starting point".
In a sense of object-oriented programming, say C#, it's the init() or constructor of the object class, that's what "entry point" meant.
For example
public class IamMain // when export and require this guy
{
public IamMain() // this is "main"
{...}
... // many others such as function, properties, etc.
}
If you are using Express > 4.0, you could go for serve-favicon
If, like me, you prefer to deal with strongly typed objects** go with:
MyObj obj = JsonConvert.DeserializeObject<MyObj>(jsonString);
This way you get to use intellisense and compile time type error checking.
You can easily create the required objects by copying your JSON into memory and pasting it as JSON objects (Visual Studio -> Edit -> Paste Special -> Paste JSON as Classes).
See here if you don't have that option in Visual Studio.
You will also need to make sure your JSON is valid. Add your own object at the start if it is just an array of objects. i.e. {"obj":[{},{},{}]}
** I know that dynamic makes things easier sometimes but I'm a bit ol'skool with this.
For VS Code 1.38 or if you could not find any "lightbulb" button. Pay close attention to the greyed out text above the conflicts; there is a list of actions you can take.
os.path.splitext() won't work if there are multiple dots in the extension.
For example, images.tar.gz
>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> print os.path.splitext(file_name)[0]
images.tar
You can just find the index of the first dot in the basename and then slice the basename to get just the filename without extension.
>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> index_of_dot = file_name.index('.')
>>> file_name_without_extension = file_name[:index_of_dot]
>>> print file_name_without_extension
images
The best and most efficient way is to catch the "table not found" exception: this avoids the overhead of checking if the table exists twice; and doesn't suffer from the problem that if the DROP fails for some other reason (that might be important) the exception is still raised to the caller:
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE ' || table_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
END;
ADDENDUM For reference, here are the equivalent blocks for other object types:
Sequence
BEGIN
EXECUTE IMMEDIATE 'DROP SEQUENCE ' || sequence_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -2289 THEN
RAISE;
END IF;
END;
View
BEGIN
EXECUTE IMMEDIATE 'DROP VIEW ' || view_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
END;
Trigger
BEGIN
EXECUTE IMMEDIATE 'DROP TRIGGER ' || trigger_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -4080 THEN
RAISE;
END IF;
END;
Index
BEGIN
EXECUTE IMMEDIATE 'DROP INDEX ' || index_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -1418 THEN
RAISE;
END IF;
END;
Column
BEGIN
EXECUTE IMMEDIATE 'ALTER TABLE ' || table_name
|| ' DROP COLUMN ' || column_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -904 AND SQLCODE != -942 THEN
RAISE;
END IF;
END;
Database Link
BEGIN
EXECUTE IMMEDIATE 'DROP DATABASE LINK ' || dblink_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -2024 THEN
RAISE;
END IF;
END;
Materialized View
BEGIN
EXECUTE IMMEDIATE 'DROP MATERIALIZED VIEW ' || mview_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -12003 THEN
RAISE;
END IF;
END;
Type
BEGIN
EXECUTE IMMEDIATE 'DROP TYPE ' || type_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -4043 THEN
RAISE;
END IF;
END;
Constraint
BEGIN
EXECUTE IMMEDIATE 'ALTER TABLE ' || table_name
|| ' DROP CONSTRAINT ' || constraint_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -2443 AND SQLCODE != -942 THEN
RAISE;
END IF;
END;
Scheduler Job
BEGIN
DBMS_SCHEDULER.drop_job(job_name);
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -27475 THEN
RAISE;
END IF;
END;
User / Schema
BEGIN
EXECUTE IMMEDIATE 'DROP USER ' || user_name;
/* you may or may not want to add CASCADE */
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -1918 THEN
RAISE;
END IF;
END;
Package
BEGIN
EXECUTE IMMEDIATE 'DROP PACKAGE ' || package_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -4043 THEN
RAISE;
END IF;
END;
Procedure
BEGIN
EXECUTE IMMEDIATE 'DROP PROCEDURE ' || procedure_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -4043 THEN
RAISE;
END IF;
END;
Function
BEGIN
EXECUTE IMMEDIATE 'DROP FUNCTION ' || function_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -4043 THEN
RAISE;
END IF;
END;
Tablespace
BEGIN
EXECUTE IMMEDIATE 'DROP TABLESPACE' || tablespace_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -959 THEN
RAISE;
END IF;
END;
Synonym
BEGIN
EXECUTE IMMEDIATE 'DROP SYNONYM ' || synonym_name;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -1434 THEN
RAISE;
END IF;
END;
Use the Python set type. That would be the most Pythonic. :)
Also, since it's native, it should be the most optimized method too.
See:
http://docs.python.org/library/stdtypes.html#set
http://docs.python.org/library/sets.htm (for older python)
# Using Python 2.7 set literal format.
# Otherwise, use: l1 = set([1,2,6,8])
#
l1 = {1,2,6,8}
l2 = {2,3,5,8}
l3 = l1 - l2
To solve this either you down-grade the Django
to any version lesser than 2.0.
pip
install Django==1.11.29
.
If you're using zsh, you can use multiple redirections, so you don't even need tee
:
./cmd 1>&1 2>&2 1>out_file 2>err_file
Here you're simply redirecting each stream to itself and the target file.
Full example
% (echo "out"; echo "err">/dev/stderr) 1>&1 2>&2 1>/tmp/out_file 2>/tmp/err_file
out
err
% cat /tmp/out_file
out
% cat /tmp/err_file
err
Note that this requires the MULTIOS
option to be set (which is the default).
MULTIOS
Perform implicit
tee
s orcat
s when multiple redirections are attempted (see Redirection).
It could very well be the case that people who sign up for your service are entering emails with typing mistakes that you do not correct. For example: chris@gmial.com -or- james@hotnail.com.
And such domains are configured to be used as spamtraps which will automatically flag your email server's IP and/or domain and hurt its reputation.
To avoid this, do a double-check for the email address that is entered upon your product subscription. Also, send a confirmation email to really ensure that this email address is 100% validated by a human being that is entering the confirmation email, before you send them the product key or accept their subscription. The verification email should require the recipient to click a link or reply in order to really confirm that the owner of the mailbox is the person who signed up.
listA.retainAll(listB);
// listA now contains only the elements which are also contained in listB.
If you want to avoid that changes are being affected in listA
, then you need to create a new one.
List<Integer> common = new ArrayList<Integer>(listA);
common.retainAll(listB);
// common now contains only the elements which are contained in listA and listB.
if you do ctrl-z
and then type exit
it will close background applications.
Ctrl+Q
is another good way to kill the application.
Why not implement this in a UITableViewController instead? The keyboard won't hide any text fields when its shown.
There are two ways to handle this.
1) Check the event.target result in your callback to see if it matches your parent div
var g_ParentDiv;
function OnMouseOut(event) {
if (event.target != g_ParentDiv) {
return;
}
// handle mouse event here!
};
window.onload = function() {
g_ParentDiv = document.getElementById("parentdiv");
g_ParentDiv.onmouseout = OnMouseOut;
};
<div id="parentdiv">
<img src="childimage.jpg" id="childimg" />
</div>
2) Or use event capturing and call event.stopPropagation in the callback function
var g_ParentDiv;
function OnMouseOut(event) {
event.stopPropagation(); // don't let the event recurse into children
// handle mouse event here!
};
window.onload = function() {
g_ParentDiv = document.getElementById("parentdiv");
g_ParentDiv.addEventListener("mouseout", OnMouseOut, true); // pass true to enable event capturing so parent gets event callback before children
};
<div id="parentdiv">
<img src="childimage.jpg" id="childimg" />
</div>
Just a comment on importing jars into Eclipse (plug-in development) projects:
In case you are developing Eclipse plug-ins, it makes sense to use Eclipse's native bundling mechanism instead of just importing the jar into a plug-in project. Eclipse (or better its underlying OSGi runtime, Equinox) uses so-called bundles which contain some more information than plain jars (e.g., version infos, dependencies to other bundles, exported packages; see the MANIFEST.MF file). Because of this information, OSGi bundles can be dynamically loaded/unloaded and there is automatic dependency resolution available in an OSGi/Eclipse runtime. Hence, using OSGi bundles instead of plain jars (contained inside another OSGi bundle) has some advantages.
(BTW: Eclipse plug-ins are the same thing as OSGi bundles.)
There is a good chance that somebody already bundled a certain (3rd party) library as an OSGi bundle. You might want to take a look at the following bundle repositories:
Left Right Arrow with hover effect using Roko C. Buljan box-shadow trick
.arr {_x000D_
display: inline-block;_x000D_
padding: 1.2em;_x000D_
box-shadow: 8px 8px 0 2px #777 inset;_x000D_
}_x000D_
.arr.left {_x000D_
transform: rotate(-45deg);_x000D_
}_x000D_
.arr.right {_x000D_
transform: rotate(135deg);_x000D_
}_x000D_
.arr:hover {_x000D_
box-shadow: 8px 8px 0 2px #000 inset_x000D_
}
_x000D_
<div class="arr left"></div>_x000D_
<div class="arr right"></div>
_x000D_
You, or most likely your sysadmin, will need to login as root and run the chown command: http://www.computerhope.com/unix/uchown.htm
Through this command you will become the owner of the file.
Or, you can be a member of a group that owns this file and then you can use chmod.
But, talk with your sysadmin.
make an example:
var body = document.body,
btn = document.getElementById( 'id' );
body.addEventListener( 'click', function( event ) {
console.log( event.currentTarget === body );
console.log( event.target === btn );
}, false );
when you click 'btn', and 'true' and 'true' will be appeared!
another simple one-liner:
var ob = {};
Object.keys(ob).length // 0
'hg forget
' is just shorthand for 'hg remove -Af
'. From the 'hg remove
' help:
...and -Af can be used to remove files from the next revision without deleting them from the working directory.
Bottom line: 'remove
' deletes the file from your working copy on disk (unless you uses -Af
) and 'forget
' doesn't.
I did some modifications on the jquery-ui.min.js:
//Line 319 ORIG:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").appendTo(d(...
// NEW:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").addClass("typeahead").addClass("dropdown-menu").appendTo(d(...
// Line 328 ORIG:
this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr...
// NEW:this.element.attr....
// Line 329 ORIG:
this.active=a.eq(0).children("a")
this.active.children("a")
// NEW:
this.active=a.eq(0).addClass("active").children("a")
this.active.removeClass("active").children("a")`
and add following css
.dropdown-menu {
max-width: 920px;
}
.ui-menu-item {
cursor: pointer;
}
Works perfect.
function isNumeric(x) {
return parseFloat(x) == x;
}
Test cases from question:
console.log('trues');
console.log(isNumeric('-1'));
console.log(isNumeric('-1.5'));
console.log(isNumeric('0'));
console.log(isNumeric('0.42'));
console.log(isNumeric('.42'));
console.log('falses');
console.log(isNumeric('99,999'));
console.log(isNumeric('0x89f'));
console.log(isNumeric('#abcdef'));
console.log(isNumeric('1.2.3'));
console.log(isNumeric(''));
console.log(isNumeric('blah'));
Some more test cases:
console.log('trues');
console.log(isNumeric(0));
console.log(isNumeric(-1));
console.log(isNumeric(-500));
console.log(isNumeric(15000));
console.log(isNumeric(0.35));
console.log(isNumeric(-10.35));
console.log(isNumeric(2.534e25));
console.log(isNumeric('2.534e25'));
console.log(isNumeric('52334'));
console.log(isNumeric('-234'));
console.log(isNumeric(Infinity));
console.log(isNumeric(-Infinity));
console.log(isNumeric('Infinity'));
console.log(isNumeric('-Infinity'));
console.log('falses');
console.log(isNumeric(NaN));
console.log(isNumeric({}));
console.log(isNumeric([]));
console.log(isNumeric(''));
console.log(isNumeric('one'));
console.log(isNumeric(true));
console.log(isNumeric(false));
console.log(isNumeric());
console.log(isNumeric(undefined));
console.log(isNumeric(null));
console.log(isNumeric('-234aa'));
Note that it considers infinity a number.
To prevent scrolling on modern mobile browsers you need to add the passive: false. I had been pulling my hair out getting this to work until I found this solution. I have only found this mentioned in one other place on the internet.
function preventDefault(e){_x000D_
e.preventDefault();_x000D_
}_x000D_
_x000D_
function disableScroll(){_x000D_
document.body.addEventListener('touchmove', preventDefault, { passive: false });_x000D_
}_x000D_
function enableScroll(){_x000D_
document.body.removeEventListener('touchmove', preventDefault);_x000D_
}
_x000D_
So I had a lot of problems with all of the solutions mentioned so far...
I have a local package that I want to always reference (rather than npm link) because it won't be used outside of this project (for now) and also won't be uploaded to an npm repository for wide use as of yet.
I also need it to work on Windows AND Unix, so sym-links aren't ideal.
Pointing to the tar.gz result of (npm package) works for the dependent npm package folder, however this causes issues with the npm cache if you want to update the package. It doesn't always pull in the new one from the referenced npm package when you update it, even if you blow away node_modules and re-do your npm-install for your main project.
so.. This is what worked well for me!
Main Project's Package.json File Snippet:
"name": "main-project-name",
"version": "0.0.0",
"scripts": {
"ng": "ng",
...
"preinstall": "cd ../some-npm-package-angular && npm install && npm run build"
},
"private": true,
"dependencies": {
...
"@com/some-npm-package-angular": "file:../some-npm-package-angular/dist",
...
}
This achieves 3 things:
I hope this is clear, and helps someone out.
The tar.gz approach also sort of works..
npm install (file path) also sort of works.
This was all based off of a generated client from an openapi spec that we wanted to keep in a separate location (rather than using copy-pasta for individual files)
====== UPDATE: ======
There are additional errors with a regular development flow with the above solution, as npm's versioning scheme with local files is absolutely terrible. If your dependent package changes frequently, this whole scheme breaks because npm will cache your last version of the project and then blow up when the SHA hash doesn't match anymore with what was saved in your package-lock.json file, among other issues.
As a result, I recommend using the *.tgz approach with a version update for each change. This works by doing three things.
First:
For your dependent package, use the npm library "ng-packagr". This is automatically added to auto-generated client packages created by the angular-typescript code generator for OpenAPI 3.0.
As a result the project that I'm referencing has a "scripts" section within package.json that looks like this:
"scripts": {
"build": "ng-packagr -p ng-package.json",
"package": "npm install && npm run build && cd dist && npm pack"
},
And the project referencing this other project adds a pre-install step to make sure the dependent project is up to date and rebuilt before building itself:
"scripts": {
"preinstall": "npm run clean && cd ../some-npm-package-angular && npm run package"
},
Second
Reference the built tgz npm package from your main project!
"dependencies": {
"@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-<packageVersion>.tgz",
...
}
Third
Update the dependent package's version EVERY TIME you update the dependent package. You'll also have to update the version in the main project.
If you do not do this, NPM will choke and use a cached version and explode when the SHA hash doesn't match. NPM versions file-based packages based on the filename changing. It won't check the package itself for an updated version in package.json, and the NPM team stated that they will not fix this, but people keep raising the issue: https://github.com/microsoft/WSL/issues/348
for now, just update the:
"version": "1.0.0-build5",
In the dependent package's package.json file, then update your reference to it in the main project to reference the new filename, ex:
"dependencies": {
"@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-1.0.0-build5.tgz",
...
}
You get used to it. Just update the two package.json files - version then the ref to the new filename.
Hope that helps someone...
Normally, JavaScript code has global scope in the application. When we declare global variable in it, there is a chance for using the same duplicate variable in some other area of the development for some other purpose. Because of this duplication there may happen some error. So we can avoid this global variables by using immediately invoking function expression , this expression is self-executing expression.When we make our code inside this IIFE expression global variable will be like local scope and local variable.
Two ways we can create IIFE
(function () {
"use strict";
var app = angular.module("myModule", []);
}());
OR
(function () {
"use strict";
var app = angular.module("myModule", []);
})();
In the code snippet above, “var app” is a local variable now.
As per the docs:
You can set annotation processor argument (room.schemaLocation) to tell Room to export the schema into a folder. Even though it is not mandatory, it is a good practice to have version history in your codebase and you should commit that file into your version control system (but don't ship it with your app!).
So if you don't need to check the schema and you want to get rid of the warning, just add exportSchema = false
to your RoomDatabase
, as follows.
@Database(entities = { YourEntity.class }, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
//...
}
If you follow @mikejonesguy answer below, you will follow the good practice mentioned in the docs :).
Basically you will get a .json
file in your ../app/schemas/
folder.
And it looks something like this:
{
"formatVersion": 1,
"database": {
"version": 1,
"identityHash": "53db508c5248423325bd5393a1c88c03",
"entities": [
{
"tableName": "sms_table",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `message` TEXT, `date` INTEGER, `client_id` INTEGER)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER"
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT"
},
{
"fieldPath": "date",
"columnName": "date",
"affinity": "INTEGER"
},
{
"fieldPath": "clientId",
"columnName": "client_id",
"affinity": "INTEGER"
}
],
"primaryKey": {
"columnNames": [
"id"
],
"autoGenerate": true
},
"indices": [],
"foreignKeys": []
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"53db508c5248423325bd5393a1c88c03\")"
]
}
}
If my understanding is correct, you will get such a file with every database version update, so that you can easily follow the history of your db.
Yes. Pass gcc the -E
option. This will output preprocessed source code.
You need to use the OutputStreamWriter
class as the writer parameter for your BufferedWriter
. It does accept an encoding. Review javadocs for it.
Somewhat like this:
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("jedis.txt"), "UTF-8"
));
Or you can set the current system encoding with the system property file.encoding
to UTF-8.
java -Dfile.encoding=UTF-8 com.jediacademy.Runner arg1 arg2 ...
You may also set it as a system property at runtime with System.setProperty(...)
if you only need it for this specific file, but in a case like this I think I would prefer the OutputStreamWriter
.
By setting the system property you can use FileWriter
and expect that it will use UTF-8 as the default encoding for your files. In this case for all the files that you read and write.
EDIT
Starting from API 19, you can replace the String "UTF-8" with StandardCharsets.UTF_8
As suggested in the comments below by tchrist, if you intend to detect encoding errors in your file you would be forced to use the OutputStreamWriter
approach and use the constructor that receives a charset encoder.
Somewhat like
CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
encoder.onMalformedInput(CodingErrorAction.REPORT);
encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("jedis.txt"),encoder));
You may choose between actions IGNORE | REPLACE | REPORT
Also, this question was already answered here.
I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?
I had to call a function once my dataService was initialized, instead, I called it inside the constructor, that worked for me.
Try this:
s = 'hello plombier pantin'
print (s.find('p'))
6
print (s.index('p'))
6
print (s.rindex('p'))
15
print (s.rfind('p'))
Keep template column inside DataGrid.Columns. This helped me resolve this issue.
Ref: DataGridTemplateColumn : Items collection must be empty before using ItemsSource.
Use:
string.replace(r"C:\Users\Josh\Desktop\20130216", "\\", "\\")
Escape the \
character.
What I did was creating my own Window and Style. Because I like to have control over everything and I didn't want some external libraries just to use a Window from it. I looked at already mentioned MahApps.Metro on GitHub
and also very nice Modern UI on GitHub. (.NET4.5 only)
There is one more it's Elysium but I really didn't try this one.
The style I did was really easy when I looked how it's done in these. Now I have my own Window and I can do whatever I want with xaml... for me it's the main reason why I did my own. And I made one more for you too :) I should probably say that I wouldn't be able to do it without exploring Modern UI it was great help. I tried to make it look like VS2012 Window. It looks like this.
Here is code (please note that it's targeting .NET4.5)
public class MyWindow : Window
{
public MyWindow()
{
this.CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, this.OnCloseWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, this.OnMaximizeWindow, this.OnCanResizeWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, this.OnMinimizeWindow, this.OnCanMinimizeWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, this.OnRestoreWindow, this.OnCanResizeWindow));
}
private void OnCanResizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = this.ResizeMode == ResizeMode.CanResize || this.ResizeMode == ResizeMode.CanResizeWithGrip;
}
private void OnCanMinimizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = this.ResizeMode != ResizeMode.NoResize;
}
private void OnCloseWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.CloseWindow(this);
}
private void OnMaximizeWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.MaximizeWindow(this);
}
private void OnMinimizeWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.MinimizeWindow(this);
}
private void OnRestoreWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.RestoreWindow(this);
}
}
And here resources:
<BooleanToVisibilityConverter x:Key="bool2VisibilityConverter" />
<Color x:Key="WindowBackgroundColor">#FF2D2D30</Color>
<Color x:Key="HighlightColor">#FF3F3F41</Color>
<Color x:Key="BlueColor">#FF007ACC</Color>
<Color x:Key="ForegroundColor">#FFF4F4F5</Color>
<SolidColorBrush x:Key="WindowBackgroundColorBrush" Color="{StaticResource WindowBackgroundColor}"/>
<SolidColorBrush x:Key="HighlightColorBrush" Color="{StaticResource HighlightColor}"/>
<SolidColorBrush x:Key="BlueColorBrush" Color="{StaticResource BlueColor}"/>
<SolidColorBrush x:Key="ForegroundColorBrush" Color="{StaticResource ForegroundColor}"/>
<Style x:Key="WindowButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Padding" Value="1" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter x:Name="contentPresenter"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
Margin="{TemplateBinding Padding}"
RecognizesAccessKey="True" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource HighlightColorBrush}" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="{DynamicResource BlueColorBrush}" />
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter TargetName="contentPresenter" Property="Opacity" Value=".5" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="MyWindowStyle" TargetType="local:MyWindow">
<Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
<Setter Property="Background" Value="{DynamicResource WindowBackgroundBrush}"/>
<Setter Property="ResizeMode" Value="CanResizeWithGrip" />
<Setter Property="UseLayoutRounding" Value="True" />
<Setter Property="TextOptions.TextFormattingMode" Value="Display" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyWindow">
<Border x:Name="WindowBorder" Margin="{Binding Source={x:Static SystemParameters.WindowNonClientFrameThickness}}" Background="{StaticResource WindowBackgroundColorBrush}">
<Grid>
<Border BorderThickness="1">
<AdornerDecorator>
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="25" />
<RowDefinition Height="*" />
<RowDefinition Height="15" />
</Grid.RowDefinitions>
<ContentPresenter Grid.Row="1" Grid.RowSpan="2" Margin="7"/>
<Rectangle x:Name="HeaderBackground" Height="25" Fill="{DynamicResource WindowBackgroundColorBrush}" VerticalAlignment="Top" Grid.Row="0"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" WindowChrome.IsHitTestVisibleInChrome="True" Grid.Row="0">
<Button Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}" ToolTip="minimize" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
<Path Data="M0,6 L8,6 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2" />
</Grid>
</Button.Content>
</Button>
<Grid Margin="1,0,1,0">
<Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}" ToolTip="restore" Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" UseLayoutRounding="True" RenderTransform="1,0,0,1,.5,.5">
<Path Data="M2,0 L8,0 L8,6 M0,3 L6,3 M0,2 L6,2 L6,8 L0,8 Z" Width="8" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1" />
</Grid>
</Button.Content>
</Button>
<Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}" ToolTip="maximize" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="31" Height="25">
<Path Data="M0,1 L9,1 L9,8 L0,8 Z" Width="9" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2" />
</Grid>
</Button.Content>
</Button>
</Grid>
<Button Command="{Binding Source={x:Static SystemCommands.CloseWindowCommand}}" ToolTip="close" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
<Path Data="M0,0 L8,7 M8,0 L0,7 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1.5" />
</Grid>
</Button.Content>
</Button>
</StackPanel>
<TextBlock x:Name="WindowTitleTextBlock" Grid.Row="0" Text="{TemplateBinding Title}" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" Margin="8 -1 0 0" FontSize="16" Foreground="{TemplateBinding Foreground}"/>
<Grid Grid.Row="2">
<Path x:Name="ResizeGrip" Visibility="Collapsed" Width="12" Height="12" Margin="1" HorizontalAlignment="Right"
Stroke="{StaticResource BlueColorBrush}" StrokeThickness="1" Stretch="None" Data="F1 M1,10 L3,10 M5,10 L7,10 M9,10 L11,10 M2,9 L2,11 M6,9 L6,11 M10,9 L10,11 M5,6 L7,6 M9,6 L11,6 M6,5 L6,7 M10,5 L10,7 M9,2 L11,2 M10,1 L10,3" />
</Grid>
</Grid>
</AdornerDecorator>
</Border>
<Border BorderBrush="{StaticResource BlueColorBrush}" BorderThickness="1" Visibility="{Binding IsActive, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Converter={StaticResource bool2VisibilityConverter}}" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="WindowState" Value="Maximized">
<Setter TargetName="Maximize" Property="Visibility" Value="Collapsed" />
<Setter TargetName="Restore" Property="Visibility" Value="Visible" />
<Setter TargetName="LayoutRoot" Property="Margin" Value="7" />
</Trigger>
<Trigger Property="WindowState" Value="Normal">
<Setter TargetName="Maximize" Property="Visibility" Value="Visible" />
<Setter TargetName="Restore" Property="Visibility" Value="Collapsed" />
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="ResizeMode" Value="CanResizeWithGrip" />
<Condition Property="WindowState" Value="Normal" />
</MultiTrigger.Conditions>
<Setter TargetName="ResizeGrip" Property="Visibility" Value="Visible" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="WindowChrome.WindowChrome">
<Setter.Value>
<WindowChrome CornerRadius="0" GlassFrameThickness="1" UseAeroCaptionButtons="False" />
</Setter.Value>
</Setter>
</Style>
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
The best way to catch the position is by FindIndex
This function is available only for List<>
Example
int id = listMyObject.FindIndex(x => x.Id == 15);
If you have enumerator or array use this way
int id = myEnumerator.ToList().FindIndex(x => x.Id == 15);
or
int id = myArray.ToList().FindIndex(x => x.Id == 15);
May I add something. If you are using currency you should use Scale(2), and you should probably figure out a round method.
It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.
But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.
To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.
For SEO reason:
<div itemscope itemtype="https://schema.org/Organization">
<p id="logo"><a href="/"><span itemprop="Brand">Your business</span> <span class="icon fa-stg"></span> - <span itemprop="makesOffer">sell staff</span></a></p>
</div>
<h1>Your awesome title</h1>
Tried all solutions here but these 2 steps solved the issue:
1) manual update of open-ssl from here:
https://slproweb.com/products/Win32OpenSSL.html
2) update OpenSSL using conda update openssl
command in the Anaconda Prompt
solved the issue!
Just delete the folder highlighted below. Depending on your Android Studio version, mine is 3.5 and reopen Android studio.
I tried in vain to find the current location of this file for version 2020. When navigating to Help > Edit Custom Properties
a new (empty) file is created at appData/Roaming/JetBrains/IntelliJIdea2020.1/idea.properties
. There is no /bin directory as some tutorials suggest. However, neither adding the block from the accepted answer to this file nor adding the same file to /bin resulted in an update to my configuration.
I finally discovered that a reference to the same property exists in appData/Roaming/JetBrains/IntelliJIdea2020.1/idea64.exe.vmoptions
. It looks like this:
-Didea.max.intellisense.filesize=3470
I changed it to this, which should be adequate for my needs:
-Didea.max.intellisense.filesize=9999
This strikes me as a bug in this version where the behavior of the menu item doesn't reflect what's needed, but it may also be the case that my particular setup is somehow different than stock. I do have PyCharm and the JDK installed.
I know it's not the best solution, but the best practice:
$("#root").append(child);
setTimeout(function(){
// Action after append
},100);
Gasp, use:
while (!false)
{
}
OR as jsight pointed out, you may want to be doubly sure:
while (!false && true)
{
}
Before people yell at me, it's all the same CIL code, I checked :)
I had an issue with Page.ClientScript.RegisterStartUpScript - I wasn't using an update panel, but the control was cached. This meant that I had to insert the script into a Literal (or could use a PlaceHolder) so when rendered from the cache the script is included.
A similar solution might work for you.
Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.
Well, this question was asked and answered way back in 2011, but there is nullptr
in C++11. That's all I'm using currently.
You can read more from Stack Overflow and also from this article.
Heavily influenced by Ruslan Tushov's library, I've created my own small library. Just add the script in the <head>
and it will patch setInterval
and setTimeout
with ones that use WebWorker
.
Running the command prompt or Powershell ISE as an administrator fixed this for me.
You can use Filehound to do this.
For example: find all .html files in /tmp:
const Filehound = require('filehound');
Filehound.create()
.ext('html')
.paths("/tmp")
.find((err, htmlFiles) => {
if (err) return console.error("handle err", err);
console.log(htmlFiles);
});
For further information (and examples), check out the docs: https://github.com/nspragg/filehound
Disclaimer: I'm the author.
Try this : write below code on body & feel the magic :)
body oncontextmenu="return false"
If startDate and endDate are indeed date objects you could convert them to number of milliseconds since midnight Jan 1, 1970, like this:
var startTime = startDate.getTime(), endTime = endDate.getTime();
Then you could loop from one to another incrementing loopTime by 86400000 (1000*60*60*24) - number of milliseconds in one day:
for(loopTime = startTime; loopTime < endTime; loopTime += 86400000)
{
var loopDay=new Date(loopTime)
//use loopDay as you wish
}
You are attempting to attach an event listener function before the element is loaded. Place fun()
inside an onload
event listener function. Call f1()
within this function, as the onclick
attribute will be ignored.
function f1() {
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
}
window.onload = function() {
document.getElementById("Save").onclick = function fun() {
alert("hello");
f1();
//validation code to see State field is mandatory.
}
}
To obtain the current stable version of the NuGet package use:
https://www.nuget.org/api/v2/package/{packageID}
Same thing just happened to me on Google Chrome v22.0.1221.1 (Nvidia GPU).
The workaround was to disable GPU compositing on all pages (setting available on chrome://flags/
)
If it happens in Chrome version > 45.x, See answer https://stackoverflow.com/a/32955808/293023 by @detale.
Use google-chrome -disable-gpu
from the command line to temporary disable gpu.
JULI logging levels for Tomcat
SEVERE - Serious failures
WARNING - Potential problems
INFO - Informational messages
CONFIG - Static configuration messages
FINE - Trace messages
FINER - Detailed trace messages
FINEST - Highly detailed trace messages
You can find here more https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/pasoe-admin/tomcat-logging.html
java 8 base solution:
List duplicates =
list.stream().collect(Collectors.groupingBy(Function.identity()))
.entrySet()
.stream()
.filter(e -> e.getValue().size() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase could equally well be used the opposite way, it's just that language users tend to follow the language authors.
having said that, i think most libraries tend to roughly follow a simplification of Java's CamelCase. I find Douglas Crockford advices tasteful enough for me.
Use sp_executesql
to execute any SQL, e.g.
DECLARE @tbl sysname,
@sql nvarchar(4000),
@params nvarchar(4000),
@count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO @tbl
IF @@fetch_status <> 0
BREAK
SELECT @sql =
N' SELECT @cnt = COUNT(*) FROM dbo.' + quotename(@tbl) +
N' WHERE LastUpdated BETWEEN @fromdate AND ' +
N' coalesce(@todate, ''99991231'')'
SELECT @params = N'@fromdate datetime, ' +
N'@todate datetime = NULL, ' +
N'@cnt int OUTPUT'
EXEC sp_executesql @sql, @params, '20060101', @cnt = @count OUTPUT
PRINT @tbl + ': ' + convert(varchar(10), @count) + ' modified rows.'
END
DEALLOCATE tblcur
Create a vectorized method
def calc_xb_minus_xa(df):
time_dict = {
'<Minute>': 'm',
'<Hour>': 'h',
'<Day>': 'D',
'<Week>': 'W',
'<Month>': 'M',
'<Year>': 'Y'
}
time_delta = df.at[df.index[0], 'end_time'] - df.at[df.index[0], 'open_time']
offset_base_name = str(to_offset(time_delta).base)
time_term = time_dict.get(offset_base_name)
result = (df.end_time - df.open_time) / np.timedelta64(1, time_term)
return result
Then in your df do:
df['x'] = calc_xb_minus_xa(df)
This will work for minutes, hours, days, weeks, month and Year. open_time and end_time need to change according your df
They are binary large objects, you can use them to store binary data such as images or serialized objects among other things.
Several options, by order of most appropriate way:
System.Environment.Exit
(not portable! see below)Edited 9/2013 to improve readability
Returning with a specific exit code: As Servy points out in the comments, you can declare Main with an int
return type and return an error code that way. So there really is no need to use Environment.Exit unless you need to terminate with an exit code and can't possibly do it in the Main method. Most probably you can avoid that by throwing an exception, and returning an error code in Main if any unhandled exception propagates there. If the application is multi-threaded you'll probably need even more boilerplate to properly terminate with an exit code so you may be better off just calling Environment.Exit.
Another point against using Evironment.Exit
- even when writing multi-threaded applications - is reusability. If you ever want to reuse your code in an environment that makes Environment.Exit
irrelevant (such as a library that may be used in a web server), the code will not be portable. The best solution still is, in my opinion, to always use exceptions and/or return values that represent that the method reached some error/finish state. That way, you can always use the same code in any .NET environment, and in any type of application. If you are writing specifically an app that needs to return an exit code or to terminate in a way similar to what Environment.Exit
does, you can then go ahead and wrap the thread at the highest level and handle the errors/exceptions as needed.
Although its an old question let me give my input on it as well.
abstract class: Inside abstract class we can declare instance variables, which are required to the child class
Interface: Inside interface every variables is always public static and final we cannot declare instance variables
abstract class: Abstract class can talk about state of object
Interface: Interface can never talk about state of object
abstract class: Inside Abstract class we can declare constructors
Interface: Inside interface we cannot declare constructors as purpose of
constructors is to initialize instance variables. So what
is the need of constructor there if we cannot have instance
variables in interfaces.
abstract class: Inside abstract class we can declare instance and static blocks
Interface: Interfaces cannot have instance and static blocks.
abstract class: Abstract class cannot refer lambda expression
Interfaces: Interfaces with single abstract method can refer lambda expression
abstract class: Inside abstract class we can override OBJECT CLASS methods
Interfaces: We cannot override OBJECT CLASS methods inside interfaces.
I will end on the note that:
Default method concepts/static method concepts in interface came just to save implementation classes but not to provide meaningful useful implementation. Default methods/static methods are kind of dummy implementation, "if you want you can use them or you can override them (in case of default methods) in implementation class" Thus saving us from implementing new methods in implementation classes whenever new methods in interfaces are added. Therefore interfaces can never be equal to abstract classes.
Try the following I found here
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
String result = data.toURI();
// ...
}
}
I am a newbie to the iOS app development. I was practising to develop iOS apps from the very beginning and while running a very basic Hello World app, I also faced same issue that only a black blank screen appears after building and running the app in iOS simulator. Somehow while struggling to find out a solution to the problem I accidentally clicked Window-->Scale-->50% in iOS simulator and it did solve my problem. I could then see the Home page with my app and clicking on app icon I was able to run my app successfully. App versions: Xcode 5.1 iOS Simulator: 7.1 OSX: 10.9.3
I see similar answers on here... but not mine...
This is how I am unfortunatley going to deal with it... I like the len(join(arr)) > 0 approach, but it wouldn't work if the array was an array of emptystrings...
Public Function arrayLength(arr As Variant) As Long
On Error GoTo handler
Dim lngLower As Long
Dim lngUpper As Long
lngLower = LBound(arr)
lngUpper = UBound(arr)
arrayLength = (lngUpper - lngLower) + 1
Exit Function
handler:
arrayLength = 0 'error occured. must be zero length
End Function
From http://en.wikipedia.org/wiki/Printf_format_string
use 0 instead of spaces to pad a field when the width option is specified. For example, printf("%2d", 3)
results in " 3", while printf("%02d", 3)
results in "03".
you can also try this in sql-server !!
select a.city,a.total + b.total as mytotal from [dbo].[cash] a join [dbo].[cheque] b on a.city=b.city
or try using sum,union
select sum(total) as mytotal,city
from
(
select * from cash union
select * from cheque
) as vij
group by city
@Janei: my first comment here is about your sample ;)
I think if you do like this, you want to take 4, then applying the sort on these 4.
var dados = from d in dc.tbl_News.Take(4)
orderby d.idNews descending
select new
{
d.idNews,
d.titleNews,
d.textNews,
d.dateNews,
d.imgNewsThumb
};
Different than sorting whole tbl_News by idNews descending and then taking 4
var dados = (from d in dc.tbl_News orderby d.idNews descending select new { d.idNews, d.titleNews, d.textNews, d.dateNews, d.imgNewsThumb }).Take(4);
no ? results may be different.
This table shows the difference. protected internal
is the same as protected
, except it also allows access from other classes in the same assembly.
If you want to reset your table, you can do
truncate table TableName
truncate needs privileges, and you can't use it if your table has dependents (another tables that have FK of your table,
Suppose I have a file named file_name
as following:
this is python
it is file handling
this is editing of line
We have to replace line 2 with "modification is done":
f=open("file_name","r+")
a=f.readlines()
for line in f:
if line.startswith("rai"):
p=a.index(line)
#so now we have the position of the line which to be modified
a[p]="modification is done"
f.seek(0)
f.truncate() #ersing all data from the file
f.close()
#so now we have an empty file and we will write the modified content now in the file
o=open("file_name","w")
for i in a:
o.write(i)
o.close()
#now the modification is done in the file
if (!String.prototype.hasOwnProperty('addSlashes')) {
String.prototype.addSlashes = function() {
return this.replace(/&/g, '&') /* This MUST be the 1st replacement. */
.replace(/'/g, ''') /* The 4 other predefined entities, required. */
.replace(/"/g, '"')
.replace(/\\/g, '\\\\')
.replace(/</g, '<')
.replace(/>/g, '>').replace(/\u0000/g, '\\0');
}
}
Usage: alert(str.addSlashes());
I don't think the standard HTML select will display HTML content. I'd suggest checking out Bootstrap select: http://silviomoreto.github.io/bootstrap-select/
It has several options for displaying icons or other HTML markup in the select.
<select id="mySelect" data-show-icon="true">
<option data-content="<i class='glyphicon glyphicon-cutlery'></i>">-</option>
<option data-subtext="<i class='glyphicon glyphicon-eye-open'></i>"></option>
<option data-subtext="<i class='glyphicon glyphicon-heart-empty'></i>"></option>
<option data-subtext="<i class='glyphicon glyphicon-leaf'></i>"></option>
<option data-subtext="<i class='glyphicon glyphicon-music'></i>"></option>
<option data-subtext="<i class='glyphicon glyphicon-send'></i>"></option>
<option data-subtext="<i class='glyphicon glyphicon-star'></i>"></option>
</select>
Here is a demo: https://www.codeply.com/go/l6ClKGBmLS
Alternate solution to doing shallow clone (git clone --depth=1 <URL>
) would be, if remote side supports it, to use --remote
option of git archive:
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -
Or, if remote repository in question is browse-able using some web interface like gitweb or GitHub, then there is a chance that it has 'snapshot' feature, and you can download latest version (without versioning information) from web interface.
$(element).on("click mousedown mouseup focus blur keydown change",function(e){
console.log(e);
});
That will get you a lot (but not all) of the information on if an event is fired... other than manually coding it like this, I can't think of any other way to do that.
You use new
to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.
You have no reason to use new
, since A
is an automatic variable. You can simply initialise A
using its constructor:
vector<vector<int> > A(dimension, vector<int>(dimension));
1/3/2017 --> January the 3rd 2017
Hi there, today I found this article to achieve this, the article is called "Creating an HTML UI for Desktop .NET Applications" and is intended to embed a chromium based control in a WPF application. It saved me the day.
https://www.infoq.com/articles/html-desktop-net
I hope it helps somebody else.
NOTE: it is based on DotNetBrowser, see license agreement here: https://www.teamdev.com/dotnetbrowser-licence-agreement
Sliding the space bar only works if you gave more then one input language selected.
In that case the space bar will also indicate the selected language and show arrows to indicate Sliding will change selection.
This is easy fast and changes the dictionary at the same time.
First response seems the mist accurate.
Regards
In DOS/Windows Batch most commands return an exitCode, called "errorlevel", that is a value that customarily is equal to zero if the command ends correctly, or a number greater than zero if ends because an error, with greater numbers for greater errors (hence the name).
There are a couple methods to check that value, but the original one is:
IF ERRORLEVEL value command
Previous IF test if the errorlevel returned by the previous command was GREATER THAN OR EQUAL the given value and, if this is true, execute the command. For example:
verify bad-param
if errorlevel 1 echo Errorlevel is greater than or equal 1
echo The value of errorlevel is: %ERRORLEVEL%
Findstr command return 0 if the string was found and 1 if not:
CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y
Previous code will copy the file if the string was NOT found in the file.
CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF NOT ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y
Previous code copy the file if the string was found. Try this:
findstr "string" file
if errorlevel 1 (
echo String NOT found...
) else (
echo String found
)
Try something like this:
DECLARE @userData TABLE(
name varchar(30) NOT NULL,
oldlocation varchar(30) NOT NULL
);
INSERT INTO @userData (name, oldlocation)
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30;
Some versions of tar, for example, the default versions on HP-UX (I tested 11.11 and 11.31), do not include a command line option to specify a file list, so a decent work-around is to do this:
tar cvf allfiles.tar $(cat mylist.txt)
There are following different ways to perform 360 degree animation with UIView.
Using CABasicAnimation
var rotationAnimation = CABasicAnimation()
rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: (Double.pi))
rotationAnimation.duration = 1.0
rotationAnimation.isCumulative = true
rotationAnimation.repeatCount = 100.0
view.layer.add(rotationAnimation, forKey: "rotationAnimation")
Here is an extension functions for UIView that handles start & stop rotation operations:
extension UIView {
// Start rotation
func startRotation() {
let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = NSNumber(value: Double.pi)
rotation.duration = 1.0
rotation.isCumulative = true
rotation.repeatCount = FLT_MAX
self.layer.add(rotation, forKey: "rotationAnimation")
}
// Stop rotation
func stopRotation() {
self.layer.removeAnimation(forKey: "rotationAnimation")
}
}
Now using, UIView.animation closure:
UIView.animate(withDuration: 0.5, animations: {
view.transform = CGAffineTransform(rotationAngle: (CGFloat(Double.pi))
}) { (isAnimationComplete) in
// Animation completed
}
you can use something like this :
string [] filePaths = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
instead of using "." you can type the name of the file or just the type like "*.txt" also SearchOption.AllDirectories is to search in all subfolders you can change that if you only want one level more about how to use it on here
If you want to be able to handle an error instead of blindly exiting, instead of using set -e
, use a trap
on the ERR
pseudo signal.
#!/bin/bash
f () {
errorCode=$? # save the exit code as the first thing done in the trap function
echo "error $errorCode"
echo "the command executing at the time of the error was"
echo "$BASH_COMMAND"
echo "on line ${BASH_LINENO[0]}"
# do some error handling, cleanup, logging, notification
# $BASH_COMMAND contains the command that was being executed at the time of the trap
# ${BASH_LINENO[0]} contains the line number in the script of that command
# exit the script or return to try again, etc.
exit $errorCode # or use some other value or do return instead
}
trap f ERR
# do some stuff
false # returns 1 so it triggers the trap
# maybe do some other stuff
Other traps can be set to handle other signals, including the usual Unix signals plus the other Bash pseudo signals RETURN
and DEBUG
.
One way to achieve this is
>>> pd.DataFrame(np.array([[2, 3, 4]]), columns=['A', 'B', 'C']).append(df, ignore_index=True)
Out[330]:
A B C
0 2 3 4
1 5 6 7
2 7 8 9
Generally, it's easiest to append dataframes, not series. In your case, since you want the new row to be "on top" (with starting id), and there is no function pd.prepend()
, I first create the new dataframe and then append your old one.
ignore_index
will ignore the old ongoing index in your dataframe and ensure that the first row actually starts with index 1
instead of restarting with index 0
.
Typical Disclaimer: Cetero censeo ... appending rows is a quite inefficient operation. If you care about performance and can somehow ensure to first create a dataframe with the correct (longer) index and then just inserting the additional row into the dataframe, you should definitely do that. See:
>>> index = np.array([0, 1, 2])
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[0:1] = [list(s1), list(s2)]
>>> df2
Out[336]:
A B C
0 5 6 7
1 7 8 9
2 NaN NaN NaN
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[1:] = [list(s1), list(s2)]
So far, we have what you had as df
:
>>> df2
Out[339]:
A B C
0 NaN NaN NaN
1 5 6 7
2 7 8 9
But now you can easily insert the row as follows. Since the space was preallocated, this is more efficient.
>>> df2.loc[0] = np.array([2, 3, 4])
>>> df2
Out[341]:
A B C
0 2 3 4
1 5 6 7
2 7 8 9
I think the answer is pretty simple (unless I'm missing something?)
SELECT
CASE
WHEN col1 > col2 THEN SUM(col3*col4)
ELSE 0
END AS some_product
FROM some_table
GROUP BY
CASE
WHEN col1 > col2 THEN SUM(col3*col4)
ELSE 0
END
You can put the CASE STATEMENT in the GROUP BY verbatim (minus the alias column name)
Preferred way to change the appearance/whatever of row views once the ListView is drawn is to change something in the data ListView draws from (the array of objects that is passed into your Adapter) and make sure to account for that in your getView() function, then redraw the ListView by calling
notifyDataSetChanged();
EDIT: while there is a way to do this, if you need to do this chances are doing something wrong. While are few edge cases I can think about, generally using notifyDataSetChanged()
and other built in mechanisms is a way to go.
EDIT 2: One of the common mistakes people make is trying to come up with their own way to respond to user clicking/selecting a row in the ListView, as in one of the comments to this post. There is an existing way to do this. Here's how:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/* Parameters
parent: The AdapterView where the click happened.
view: The view within the AdapterView that was clicked (this will be a view provided by the adapter)
position: The position of the view in the adapter.
id: The row id of the item that was clicked. */
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//your code here
}
});
ListView has a lot of build-in functionality and there is no need to reinvent the wheel for simpler cases. Since ListView extends AdapterView, you can set the same Listeners, such as OnItemClickListener as in the example above.
TextView tv = new TextView(this);
tv.setText("" + 4);
Box and Cox (1964) suggested a family of transformations designed to reduce nonnormality of the errors in a linear model. In turns out that in doing this, it often reduces non-linearity as well.
Here is a nice summary of the original work and all the work that's been done since: http://www.ime.usp.br/~abe/lista/pdfm9cJKUmFZp.pdf
You will notice, however, that the log-likelihood function governing the selection of the lambda power transform is dependent on the residual sum of squares of an underlying model (no LaTeX on SO -- see the reference), so no transformation can be applied without a model.
A typical application is as follows:
library(MASS)
# generate some data
set.seed(1)
n <- 100
x <- runif(n, 1, 5)
y <- x^3 + rnorm(n)
# run a linear model
m <- lm(y ~ x)
# run the box-cox transformation
bc <- boxcox(y ~ x)
(lambda <- bc$x[which.max(bc$y)])
[1] 0.4242424
powerTransform <- function(y, lambda1, lambda2 = NULL, method = "boxcox") {
boxcoxTrans <- function(x, lam1, lam2 = NULL) {
# if we set lambda2 to zero, it becomes the one parameter transformation
lam2 <- ifelse(is.null(lam2), 0, lam2)
if (lam1 == 0L) {
log(y + lam2)
} else {
(((y + lam2)^lam1) - 1) / lam1
}
}
switch(method
, boxcox = boxcoxTrans(y, lambda1, lambda2)
, tukey = y^lambda1
)
}
# re-run with transformation
mnew <- lm(powerTransform(y, lambda) ~ x)
# QQ-plot
op <- par(pty = "s", mfrow = c(1, 2))
qqnorm(m$residuals); qqline(m$residuals)
qqnorm(mnew$residuals); qqline(mnew$residuals)
par(op)
As you can see this is no magic bullet -- only some data can be effectively transformed (usually a lambda less than -2 or greater than 2 is a sign you should not be using the method). As with any statistical method, use with caution before implementing.
To use the two parameter Box-Cox transformation, use the geoR
package to find the lambdas:
library("geoR")
bc2 <- boxcoxfit(x, y, lambda2 = TRUE)
lambda1 <- bc2$lambda[1]
lambda2 <- bc2$lambda[2]
EDITS: Conflation of Tukey and Box-Cox implementation as pointed out by @Yui-Shiuan fixed.
if the device is locked with black screen run the following:
My issue was I was instatiating the player completely from start but I used an iframe instead of a wrapper div.
Shortest version to prettify existing JSON: (edit: using JSON.net)
JToken.Parse("mystring").ToString()
Input:
{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}
Output:
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{
"value": "New",
"onclick": "CreateNewDoc()"
},
{
"value": "Open",
"onclick": "OpenDoc()"
},
{
"value": "Close",
"onclick": "CloseDoc()"
}
]
}
}
}
To pretty-print an object:
JToken.FromObject(myObject).ToString()
That's a clever bit.
First, as noted in a comment, in Python 3 zip()
returns an iterator, so you need to enclose the whole thing in list()
to get an actual list back out, so as of 2020 it's actually:
list(zip(*original[::-1]))
Here's the breakdown:
[::-1]
- makes a shallow copy of the original list in reverse order. Could also use reversed()
which would produce a reverse iterator over the list rather than actually copying the list (more memory efficient).*
- makes each sublist in the original list a separate argument to zip()
(i.e., unpacks the list)zip()
- takes one item from each argument and makes a list (well, a tuple) from those, and repeats until all the sublists are exhausted. This is where the transposition actually happens.list()
converts the output of zip()
to a list.So assuming you have this:
[ [1, 2, 3],
[4, 5, 6],
[7, 8, 9] ]
You first get this (shallow, reversed copy):
[ [7, 8, 9],
[4, 5, 6],
[1, 2, 3] ]
Next each of the sublists is passed as an argument to zip
:
zip([7, 8, 9], [4, 5, 6], [1, 2, 3])
zip()
repeatedly consumes one item from the beginning of each of its arguments and makes a tuple from it, until there are no more items, resulting in (after it's converted to a list):
[(7, 4, 1),
(8, 5, 2),
(9, 6, 3)]
And Bob's your uncle.
To answer @IkeMiguel's question in a comment about rotating it in the other direction, it's pretty straightforward: you just need to reverse both the sequences that go into zip
and the result. The first can be achieved by removing the [::-1]
and the second can be achieved by throwing a reversed()
around the whole thing. Since reversed()
returns an iterator over the list, we will need to put list()
around that to convert it. With a couple extra list()
calls to convert the iterators to an actual list. So:
rotated = list(reversed(list(zip(*original))))
We can simplify that a bit by using the "Martian smiley" slice rather than reversed()
... then we don't need the outer list()
:
rotated = list(zip(*original))[::-1]
Of course, you could also simply rotate the list clockwise three times. :-)
add Internet permission in manifest
<uses-permission android:name="android.permission.INTERNET" />
than create methode as below,
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src", src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap", "returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception", e.getMessage());
return null;
}
}
now add this in your onCreate method,
ImageView img_add = (ImageView) findViewById(R.id.img_add);
img_add.setImageBitmap(getBitmapFromURL("http://www.deepanelango.me/wpcontent/uploads/2017/06/noyyal1.jpg"));
this is works for me.
You have missed out the field name id
in the second NOT LIKE
. Try:
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
The AND
in the where clause joins 2 full condition expressions such as id NOT LIKE '1%'
and can't be used to list multiple values that the id is 'not like'.
argc
is the number of command line arguments given to the program at runtime, and argv
is an array of arrays of characters (rather, an array of C-strings) containing these arguments. If you know you're not going to need the command line arguments, you can declare your main at taking a void
argument, instead:
int main(void) {
/* ... */
}
Those are the only two prototypes defined for main
as per the standards, but some compilers allow a return type of void
as well. More on this on Wikipedia.
The only way I think then to get the functionality you want would be to do something like
import junit.framework.Test;
import junit.framework.TestResult;
import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("TestEverything");
//$JUnit-BEGIN$
suite.addTestSuite(TestOne.class);
suite.addTestSuite(TestTwo.class);
suite.addTestSuite(TestThree.class);
//$JUnit-END$
}
public static void main(String[] args)
{
AllTests test = new AllTests();
Test testCase = test.suite();
TestResult result = new TestResult();
setUp();
testCase.run(result);
tearDown();
}
public void setUp() {}
public void tearDown() {}
}
I use something like this in eclipse, so I'm not sure how portable it is outside of that environment
const data = [{"b":1,"c":100},{"a":1,"b":1,"c":150},{"a":1,"b":2,"c":100},{"a":2,"b":1,"c":13}]
const result = data.reduce((r, e) => {
r['a'] += (e['a'] ? e['a'] : 0)
r['d'] += (e['b'] ? e['b'] : 0)
r['c'] += (e['c'] ? e['c'] : 0)
return r
}, {'a':0, 'd':0, 'c':0})
console.log(result)
`result` { a: 4, d: 5, c: 363 }
<!DOCTYPE html>
Otherwise IE8 is not acting right. Also you should use:
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
You should add the g
modifier so that sed performs a global substitution of the contents of the pattern buffer:
echo dog dog dos | sed -e 's:dog:log:g'
For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6
The official documentation for GNU sed
is available at http://www.gnu.org/software/sed/manual/
If the first item is to be used as a placeholder (empty value) and your select is required
then you can use the :invalid
pseudo-class to target it.
select {_x000D_
-webkit-appearance: menulist-button;_x000D_
color: black;_x000D_
}_x000D_
_x000D_
select:invalid {_x000D_
color: green;_x000D_
}
_x000D_
<select required>_x000D_
<option value="">Item1</option>_x000D_
<option value="Item2">Item2</option>_x000D_
<option value="Item3">Item3</option>_x000D_
</select>
_x000D_
Following code could be used:
ThreadLocalRandom.current().nextInt(rangeStart, rangeEndExclusive)
$limit=5; // for exemple
$query = $this->getDoctrine()->getEntityManager()->createQuery(
'// your request')
->setMaxResults($limit);
$results = $query->getResult();
// Done
Just leaving the default navbar built in with bootstrap works fine.
You just need to add the custom css below, that way everything still works as it should.
HTML:
<nav class="navbar navbar-default">
CSS:
.navbar-default {
background-color: transparent;
}
The documentation you linked actually has the answer in the link associated with the "Java class located out of the source root." Configure your source and test roots and it should work.
https://www.jetbrains.com/idea/webhelp/configuring-content-roots.html
Since you stated that these are tests you should probably go with them marked as Test Source Root instead of Source Root.
pmac72 is using GO to break down the query into batches and using an ALTER.
You appear to be running the same batch but running it twice after changing it: DROP... CREATE... edit... DROP... CREATE..
Perhaps post your exact code so we can see what is going on.
you can also add inline css for adding image as a background as per below example
<div class="item active" style="background-image: url(../../foo.png);">
I'd have to agree with what you've been hearing. When we benchmark our cluster (xhpl
and such), we always get significantly better performance with processes over threads. </anecdote>
It took me almost a month to get through this. Just now I solved this issue. In your activity's onPause() you have to include the following if condition:
if (this.isFinishing()){
//Insert your finishing code here
}
The function isFinishing() returns a boolean. True if your App is actually closing, False if your app is still running but for example the screen turns off.
Hope it helps!
Yes.
ThisWorkbook.RefreshAll
Or, if your Excel version is old enough,
Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
For Each Pivot in Sheet.PivotTables
Pivot.RefreshTable
Pivot.Update
Next
Next
Does is need to be an array? If you use an ArrayList or one of the other objects available in C#, you won't have this limitation to content with. Hashtable, IDictionnary, IList, etc.. all allow a dynamic number of elements.
You need to use the local set command below:
local set
git config user.email [email protected]
git config user.name 'Mahmoud Zalt'
local get
git config --get user.email
git config --get user.name
The local config file is in the project directory: .git/config
.
global set
git config --global user.email [email protected]
git config --global user.name 'Mahmoud Zalt'
global get
git config --global --get user.email
git config --global --get user.name
The global config file in in your home directory: ~/.gitconfig
.
Remember to quote blanks, etc, for example: 'FirstName LastName'
On Amazon Linux 2 and PHP 7.4 I finally got PHP-ZIP to install and I hope it helps someone else - by the following (note the yum install command has extra common modules also included you may not need them all):
sudo yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
sudo yum -y install https://rpms.remirepo.net/enterprise/remi-release-7.rpm
sudo yum -y install yum-utils
sudo yum-config-manager --enable remi-php74
sudo yum update
sudo yum install php php-cli php-fpm php-mysqlnd php-zip php-devel php-gd php-mcrypt php-mbstring php-curl php-xml php-pear php-bcmath php-json
sudo pecl install zip
php --modules
sudo systemctl restart httpd
you could search with
aptitude search intl
after you can choose the right one, for example
sudo aptitude install php-intl
and finally
sudo service apache2 restart
good Luck!
You may treat window as a service (eg. UI service) and pass itself to viewmodel via an interface, as such:
public interface IMainWindowAccess
{
void Close(bool result);
}
public class MainWindow : IMainWindowAccess
{
// (...)
public void Close(bool result)
{
DialogResult = result;
Close();
}
}
public class MainWindowViewModel
{
private IMainWindowAccess access;
public MainWindowViewModel(IMainWindowAccess access)
{
this.access = access;
}
public void DoClose()
{
access.Close(true);
}
}
This solution have most upsides of passing the view itself to viewmodel without having downside of breaking MVVM, because though physically view is passed to viewmodel, the latter still don't know about the former, it sees only some IMainWindowAccess
. So for instance if we wanted to migrate this solution to other platform, it would be only a matter of implementing IMainWindowAccess
properly for, say, an Activity
.
I'm posting the solution here to propose a different approach than events (though it's actually very similar), because it seems a little bit simpler than events to implement (attaching/detaching etc.), but still aligns nicely with MVVM pattern.
Install Mylyn connector for GitHub from this update site, it provides great integration: you can directly import your repositories using Import > Projects from Git > GitHub. You can set the default repository folder in Preferences > Git.
Includes are not directly supported in YAML as far as I know, you will have to provide a mechanism yourself however, this is generally easy to do.
I have used YAML as a configuration language in my python apps, and in this case often define a convention like this:
>>> main.yml <<<
includes: [ wibble.yml, wobble.yml]
Then in my (python) code I do:
import yaml
cfg = yaml.load(open("main.yml"))
for inc in cfg.get("includes", []):
cfg.update(yaml.load(open(inc)))
The only down side is that variables in the includes will always override the variables in main, and there is no way to change that precedence by changing where the "includes: statement appears in the main.yml file.
On a slightly different point, YAML doesn't support includes as its not really designed as as exclusively as a file based mark up. What would an include mean if you got it in a response to an AJAX request?
For you the get the most alike representation of your original string I recommend the unidecode module:
from unidecode import unidecode
def remove_non_ascii(text):
return unidecode(unicode(text, encoding = "utf-8"))
Then you can use it in a string:
remove_non_ascii("Ceñía")
Cenia
var clientHttp = new HttpClient();
clientHttp.Timeout = TimeSpan.FromMinutes(30);
The above is the best approach for waiting on a large request. You are confused about 30 minutes; it's random time and you can give any time that you want.
In other words, request will not wait for 30 minutes if they get results before 30 minutes. 30 min means request processing time is 30 min. When we occurred error "Task was cancelled", or large data request requirements.
Wrapping with iframe makes parent css obsolete.
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Fork(value = 1)
@Measurement(iterations = 5, time = 1)
public class StringFirstCharBenchmark {
private String source;
@Setup
public void init() {
source = "MALE";
}
@Benchmark
public String substring() {
return source.substring(0, 1);
}
@Benchmark
public String indexOf() {
return String.valueOf(source.indexOf(0));
}
}
Results:
+----------------------------------------------------------------------+
| Benchmark Mode Cnt Score Error Units |
+----------------------------------------------------------------------+
| StringFirstCharBenchmark.indexOf avgt 5 23.777 ? 5.788 ns/op |
| StringFirstCharBenchmark.substring avgt 5 11.305 ? 1.411 ns/op |
+----------------------------------------------------------------------+
I believe the correct answer is that their values are undefined. Often, they are initialized to 0 when running debug versions of the code. This is usually not the case when running release versions.
The best way I found to make this to my purpose was to increment from the max value you have in the field and for that, I used the following syntax:
var array = db.CollectionName.find({}).sort({ _id: -1 }).limit(1).toArray(); var max = max.length?max[0]+1:1;
Even if an User ID is deleted, this wont create duplicate
you cannot set this in javascript, you have to do this with html/css:
<style type="text/css" media="print">
@page { size: landscape; }
</style>
EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?
The sql query sample like this
LEFT JOIN bookings
ON rooms.id = bookings.room_type_id
AND (bookings.arrival = ?
OR bookings.departure = ?)
Laravel join with multiple conditions
->leftJoin('bookings', function($join) use ($param1, $param2) {
$join->on('rooms.id', '=', 'bookings.room_type_id');
$join->on(function($query) use ($param1, $param2) {
$query->on('bookings.arrival', '=', $param1);
$query->orOn('departure', '=',$param2);
});
})
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="LnKB" Text='edit' OnClick="LnKB_Click" >
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
protected void LnKB_Click(object sender, System.EventArgs e)
{
LinkButton lb = sender as LinkButton;
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
int x = clickedRow.RowIndex;
int id = Convert.ToInt32(yourgridviewname.Rows[x].Cells[0].Text);
lbl.Text = yourgridviewname.Rows[x].Cells[2].Text;
}
If your grep supports -R
, do:
grep -R 'string' dir/
If not, then use find
:
find dir/ -type f -exec grep -H 'string' {} +
is it possible to export without looping through all records
For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application
object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data
Option Explicit
Sub AccImport()
Dim acc As New Access.Application
acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
acc.DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:="tblExcelImport", _
Filename:=Application.ActiveWorkbook.FullName, _
HasFieldNames:=True, _
Range:="Folio_Data_original$A1:B10"
acc.CloseCurrentDatabase
acc.Quit
Set acc = Nothing
End Sub
Evidence that std::unordered_map
uses a hash map in GCC stdlibc++ 6.4
This was mentioned at: https://stackoverflow.com/a/3578247/895245 but in the following answer: What data structure is inside std::map in C++? I have given further evidence of such for the GCC stdlibc++ 6.4 implementation by:
Here is a preview of the performance characteristic graph described in that answer:
How to use a custom class and hash function with unordered_map
This answer nails it: C++ unordered_map using a custom class type as the key
Excerpt: equality:
struct Key
{
std::string first;
std::string second;
int third;
bool operator==(const Key &other) const
{ return (first == other.first
&& second == other.second
&& third == other.third);
}
};
Hash function:
namespace std {
template <>
struct hash<Key>
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
}
The way I use it is
# Have to assign back to dataframe (because it is a new copy)
df = df.some_operation(inplace=False)
Or
# No need to assign back to dataframe (because it is on the same copy)
df.some_operation(inplace=True)
CONCLUSION:
if inplace is False
Assign to a new variable;
else
No need to assign
The difference is that one modifies the data-structure itself (in-place operation) b += 1
while the other just reassigns the variable a = a + 1
.
Just for completeness:
x += y
is not always doing an in-place operation, there are (at least) three exceptions:
If x
doesn't implement an __iadd__
method then the x += y
statement is just a shorthand for x = x + y
. This would be the case if x
was something like an int
.
If __iadd__
returns NotImplemented
, Python falls back to x = x + y
.
The __iadd__
method could theoretically be implemented to not work in place. It'd be really weird to do that, though.
As it happens your b
s are numpy.ndarray
s which implements __iadd__
and return itself so your second loop modifies the original array in-place.
You can read more on this in the Python documentation of "Emulating Numeric Types".
These [
__i*__
] methods are called to implement the augmented arithmetic assignments (+=
,-=
,*=
,@=
,/=
,//=
,%=
,**=
,<<=
,>>=
,&=
,^=
,|=
). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, if x is an instance of a class with an__iadd__()
method,x += y
is equivalent tox = x.__iadd__(y)
. Otherwise,x.__add__(y)
andy.__radd__(x)
are considered, as with the evaluation ofx + y
. In certain situations, augmented assignment can result in unexpected errors (see Why doesa_tuple[i] += ["item"]
raise an exception when the addition works?), but this behavior is in fact part of the data model.
for inserting data into table you can write
insert into tablename values(column_name1,column_name2,column_name3);
but write the column_name
in the sequence as per sequence in table ...
You could use the replace method of the String
object with a function in the second parameter:
First Method (using a find and replace Object)
var findreplace = {"<" : "<", ">" : ">", "\n" : "<br/>"};
textarea = textarea.replace(new RegExp("(" + Object.keys(findreplace).map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return findreplace[s]});
Second method (using two arrays, find and replace)
var find = ["<", ">", "\n"];
var replace = ["<", ">", "<br/>"];
textarea = textarea.replace(new RegExp("(" + find.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return replace[find.indexOf(s)]});
Desired function:
function str_replace($f, $r, $s){
return $s.replace(new RegExp("(" + $f.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return $r[$f.indexOf(s)]});
}
$textarea = str_replace($find, $replace, $textarea);
EDIT
This function
admits a String
or an Array
as parameters:
function str_replace($f, $r, $s){
return $s.replace(new RegExp("(" + (typeof($f) === "string" ? $f.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&") : $f.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|")) + ")", "g"), typeof($r) === "string" ? $r : typeof($f) === "string" ? $r[0] : function(i){ return $r[$f.indexOf(i)]});
}
I check for both Wi-fi and Mobile internet as follows...
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
Obviously, It could easily be modified to check for individual specific connection types, e.g., if your app needs the potentially higher speeds of Wi-fi to work correctly etc.
As unwind noted, keyword arguments with default values can go a long way.
I'll also state that in my opinion, it goes against the spirit of Python to worry a lot about what types are passed into methods. In Python, I think it's more accepted to use duck typing -- asking what an object can do, rather than what it is.
Thus, if your method may accept a string or a tuple, you might do something like this:
def print_names(names):
"""Takes a space-delimited string or an iterable"""
try:
for name in names.split(): # string case
print name
except AttributeError:
for name in names:
print name
Then you could do either of these:
print_names("Ryan Billy")
print_names(("Ryan", "Billy"))
Although an API like that sometimes indicates a design problem.
Note that if strings has spaces then quotation marks are needed at definition and must be chopped while concatenating:
rem The retail files set
set FILES_SET="(*.exe *.dll"
rem The debug extras files set
set DEBUG_EXTRA=" *.pdb"
rem Build the DEBUG set without any
set FILES_SET=%FILES_SET:~1,-1%%DEBUG_EXTRA:~1,-1%
rem Append the closing bracket
set FILES_SET=%FILES_SET%)
echo %FILES_SET%
Cheers...
You might actually look into the internationally standardized format E.164, recommended by Twilio for example (who have a service and an API for sending SMS or phone-calls via REST requests).
This is likely to be the most universal way to store phone numbers, in particular if you have international numbers work with.
You can use phonenumber_field
library. It is port of Google's libphonenumber library, which powers Android's phone number handling
https://github.com/stefanfoulis/django-phonenumber-field
In model:
from phonenumber_field.modelfields import PhoneNumberField
class Client(models.Model, Importable):
phone = PhoneNumberField(null=False, blank=False, unique=True)
In form:
from phonenumber_field.formfields import PhoneNumberField
class ClientForm(forms.Form):
phone = PhoneNumberField()
Get phone as string from object field:
client.phone.as_e164
Normolize phone string (for tests and other staff):
from phonenumber_field.phonenumber import PhoneNumber
phone = PhoneNumber.from_string(phone_number=raw_phone, region='RU').as_e164
One note for your model: E.164 numbers have a max character length of 15.
To validate, you can employ some combination of formatting and then attempting to contact the number immediately to verify.
I believe I used something like the following on my django project:
class ReceiverForm(forms.ModelForm):
phone_number = forms.RegexField(regex=r'^\+?1?\d{9,15}$',
error_message = ("Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."))
EDIT
It appears that this post has been useful to some folks, and it seems worth it to integrate the comment below into a more full-fledged answer. As per jpotter6, you can do something like the following on your models as well:
models.py:
from django.core.validators import RegexValidator
class PhoneModel(models.Model):
...
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list
You should use glob.
glob('*.xml')
More about using glob and advanced filtering:
http://domexception.blogspot.fi/2013/08/php-using-functional-programming-for.html
Use below command:
$ git reset HEAD~1
After this you also able to view files what revert back like below response.
Unstaged changes after reset:
M application/config/config.php
M application/config/database.php
javascript does not not have a compiler like for example Java/C(You can compare it more to languages like PHP for example). If you want to write compiled code you should read the section about addons and learn C. Although this is rather complex and I don't think you need to do this but instead just write javascript.
Never mind got the way to do it.
def plotGraph(X,Y):
fignum = random.randint(0,sys.maxint)
fig = plt.figure(fignum)
### Plotting arrangements ###
return fig
------ plotting module ------
----- mainModule ----
import matplotlib.pyplot as plt
### tempDLStats, tempDLlabels are the argument
plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
plt.show()
plot1.savefig('plot1.png')
plot2.savefig('plot2.png')
plot3.savefig('plot3.png')
----- mainModule -----
Unique key :- It should be used when you have to give unique value.In the case of unique key it means null values are also allowed.Unique keys are those keys which are unique and non similar in that column like for example your pet name.it can be nothing like null and if you are asking in context of database then it must be noted that every null is different from another null in the database.EXCEPT-SQL Server where null=null is true
primary key :- It should be used when you have to give uniquely identify a row.primary is key which unique for every row in a database constraint is that it doesn't allow null in it.so, you might have seen that the database have a column which is auto increment and it is the primary key of the table. plus it can be used as a foreign key in another table.example can be orderId on a order Table,billId in a bill Table.
now coming back to situation when to use it:-
1) primary key in the column which can not be null in the table and you are using as foreign key in another table for creating relationship
2) unique key in table where it doesn't affect in table or in the whole database whether you take the null for the particular column like snacks in the restaurant it is possible you don't take snacks in a restaurant
Just connect the device to the PC with a USB cable, then copy the .apk file to the device. On the device, touch the APK file in the file explorer to install it.
You could also offer the .apk on your website. People can download it, then touch it to install.
The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.
If the URL of your website is: http://www.example.com/mywebsite/
then starting at the root level starts above the "mywebsite" folder path.
^(?!\s*$).+
will match any string that contains at least one non-space character.
So
if (Regex.IsMatch(subjectString, @"^(?!\s*$).+")) {
// Successful match
} else {
// Match attempt failed
}
should do this for you.
^
anchors the search at the start of the string.
(?!\s*$)
, a so-called negative lookahead, asserts that it's impossible to match only whitespace characters until the end of the string.
.+
will then actually do the match. It will match anything (except newline) up to the end of the string. If you want to allow newlines, you'll have to set the RegexOptions.Singleline
option.
Left over from the previous version of your question:
^\s*$
matches strings that contain only whitespace (or are empty).
The exact opposite:
^\S+$
matches only strings that consist of only non-whitespace characters, one character minimum.
Since display: none
buttons and inputs won't work in Safari and IE, I found that the easiest way, requiring no extra javascript hacks, is to simply add an absolutely positioned <button />
to the form and place it far off screen.
<form action="" method="get">
<input type="text" name="name" />
<input type="password" name="password" />
<div class="yourCustomDiv"/>
<button style="position:absolute;left:-10000px;right:9990px"/>
</form>
This works in the current version of all major browsers as of September 2016.
Obviously its reccomended (and more semantically correct) to just style the <button/>
as desired.
A gcc spec file can do the job, however all users on the machine will be affected.
See here
An adventage of use ExpectedException Rule (version 4.7) is that you can test exception message and not only the expected exception.
And using Matchers, you can test the part of message you are interested:
exception.expectMessage(containsString("income: -1000.0"));
You can use this example for dynamically calling the Where NOT IN
$user = User::where('company_id', '=', 1)->select('id)->get()->toArray(); $otherCompany = User::whereNotIn('id', $user)->get();
I am trying to do something similar to this. As commented above, I think you would want to build a new image with a custom Dockerfile (using the image you pulled as a base image), ADD
your certificate, then RUN update-ca-certificates
. This way you will have a consistent state each time you start a container from this new image.
# Dockerfile
FROM some-base-image:0.1
ADD you_certificate.crt:/container/cert/path
RUN update-ca-certificates
Let's say a docker build
against that Dockerfile produced IMAGE_ID. On the next docker run -d [any other options] IMAGE_ID
, the container started by that command will have your certificate info. Simple and reproducible.
You need to use data: {title: title}
to POST it correctly.
In the PHP code you need to echo
the value instead of return
ing it.
It looks like you're trying to replace the extension with the following code:
if (myFile[-4:] == ".asm"):
newFile = myFile[:4]+".hack"
However, you appear to have the array indexes mixed up. Try the following:
if (myFile[-4:] == ".asm"):
newFile = myFile[:-4]+".hack"
Note the use of -4
instead of just 4
in the second line of code. This explains why your program is trying to create /Use.hack
, which is the first four characters of your file name (/Use
), with .hack
appended to it.
Finds the biggest and the smallest number in the array:
int[] arr = new int[] {35,28,20,89,63,45,12};
int big = 0;
int little = 0;
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
if (arr[i] > arr[0])
{
big = arr[i];
}
else
{
little = arr[i];
}
}
Console.WriteLine("most big number inside of array is " + big);
Console.WriteLine("most little number inside of array is " + little);
For Xamarin Android this was the only solution that worked for me: another stack overflow post
If you are using AndroidClientHandler
, you need to supply a SSLSocketFactory
and a custom implementation of HostnameVerifier
with all checks disabled. To do this, you’ll need to subclass AndroidClientHandler
and override the appropriate methods.
internal class BypassHostnameVerifier : Java.Lang.Object, IHostnameVerifier
{
public bool Verify(string hostname, ISSLSession session)
{
return true;
}
}
internal class InsecureAndroidClientHandler : AndroidClientHandler
{
protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection)
{
return SSLCertificateSocketFactory.GetInsecure(1000, null);
}
protected override IHostnameVerifier GetSSLHostnameVerifier(HttpsURLConnection connection)
{
return new BypassHostnameVerifier();
}
}
And then
var httpClient = new System.Net.Http.HttpClient(new InsecureAndroidClientHandler());
Try like this:
list($width, $height) = getimagesize('path_to_image');
Make sure that:
Also try to prefix path with $_SERVER["DOCUMENT_ROOT"]
, this helps sometimes when you are not able to read files.
Just for the info, this can be done with CSS only with just minor HTML and CSS changes
HTML:
<div class="left">
Hello
</div>
<div class="right">
Hello2
</div>
<div class="center">
<div class="left1">
Bye
</div>
<div class="right1">
Bye1
</div>
</div>
CSS:
.left, .right{
margin:10px;
float:left;
border:1px solid red;
height:60px;
width:60px
}
.left:hover, .right:hover{
border:1px solid blue;
}
.right{
float :right;
}
.center{
float:left;
height:60px;
width:160px
}
.center .left1, .center .right1{
margin:10px;
float:left;
border:1px solid green;
height:60px;
width:58px;
display:none;
}
.left:hover ~ .center .left1 {
display:block;
}
.right:hover ~ .center .right1 {
display:block;
}
and the DEMO: http://jsfiddle.net/pavloschris/y8LKM/
I just found something in the TypeScript language specification, it's fairly easy. I was pretty close.
the syntax is the following:
public myCallback: (name: type) => returntype;
In my example, it would be
class CallbackTest
{
public myCallback: () => void;
public doWork(): void
{
//doing some work...
this.myCallback(); //calling callback
}
}
For anyone looking to do something similar using a reader with the stored procedure, note that the reader must be closed to retrieve the output value.
using (SqlConnection conn = new SqlConnection())
{
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add parameters
SqlParameter outputParam = cmd.Parameters.Add("@ID", SqlDbType.Int);
outputParam.Direction = ParameterDirection.Output;
conn.Open();
using(IDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
//read in data
}
}
// reader is closed/disposed after exiting the using statement
int id = outputParam.Value;
}
No, you cannot directly access the first value.
I suppose a hack for this would be to return an array of values instead of "item" and "err", and then just do
item, _ := Get(1)[0]
but I would not recommend this.
Optional arguments only work at the end of a function call. There is no way to specify a value for $y in your function without also specifying $x. Some languages support this via named parameters (VB/C# for example), but not PHP.
You can emulate this if you use an associative array for parameters instead of arguments -- i.e.
function foo(array $args = array()) {
$x = !isset($args['x']) ? 'default x value' : $args['x'];
$y = !isset($args['y']) ? 'default y value' : $args['y'];
...
}
Then call the function like so:
foo(array('y' => 'my value'));
import urllib, urllib2, cookielib
username = 'myuser'
password = 'mypassword'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()
resp.read()
is the straight html of the page you want to open, and you can use opener
to view any page using your session cookie.
127 means command not found
In your case, curl command was not found. Therefore it means, curl was not found.
You need to install/reinstall CURL. That's all. Get latest version for your OS from http://curl.haxx.se/download.html
Close RStudio before installation.
Two slices can be concatenated using append
method in the standard golang library. Which is similar to the variadic
function operation. So we need to use ...
package main
import (
"fmt"
)
func main() {
x := []int{1, 2, 3}
y := []int{4, 5, 6}
z := append([]int{}, append(x, y...)...)
fmt.Println(z)
}
output of the above code is: [1 2 3 4 5 6]
I have checked a variable if it is a boolean or not as below
console.log(isBoolean(this.myVariable));
Similarly we have
isNumber(this.myVariable);
isString(this.myvariable);
and so on.
Because the Method2
is static, all you have to do is call like this:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
If they are in different namespaces you will also need to add the namespace of AllMethods
to caller.cs in a using
statement.
If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
Update
As of C# 6, you can now also achieve this with using static
directive to call static methods somewhat more gracefully, for example:
// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}
// Caller.cs
using static Some.Namespace.AllMethods;
namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}
Further Reading
Spring has some standard events which you can handle.
To do that, you must create and register a bean that implements the ApplicationListener
interface, something like this:
package test.pack.age;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public class ApplicationListenerBean implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent) {
ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
// now you can do applicationContext.getBean(...)
// ...
}
}
}
You then register this bean within your servlet.xml
or applicationContext.xml
file:
<bean id="eventListenerBean" class="test.pack.age.ApplicationListenerBean" />
and Spring will notify it when the application context is initialized.
In Spring 3 (if you are using this version), the ApplicationListener
class is generic and you can declare the event type that you are interested in, and the event will be filtered accordingly. You can simplify a bit your bean code like this:
public class ApplicationListenerBean implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext applicationContext = event.getApplicationContext();
// now you can do applicationContext.getBean(...)
// ...
}
}