I would like to propose different solution which wasn't mentioned here which is using .URL
files:
set SHRT_LOCA=%userprofile%\Desktop\new_shortcut2.url
set SHRT_DEST=C:\Windows\write.exe
echo [InternetShortcut]> %SHRT_LOCA%
echo URL=file:///%SHRT_DEST%>> %SHRT_LOCA%
echo IconFile=%SHRT_DEST%>> %SHRT_LOCA%
echo IconIndex=^0>> %SHRT_LOCA%
Notes:
.url
files are intended to open web pages but they are working fine for any properly constructed URI.url
file extension even if "Hide extensions for known file types" option in Windows Explorer is disabledIconFile
and IconIndex
are optionalAs mentioned by many, "ctor" and double TAB works in Visual Studio 2017, but it only creates the constructor with none of the attributes.
To auto-generate with attributes (if there are any), just click on an empty line below them and press Ctrl + .. It'll display a small pop-up from which you can select the "Generate Constructor..." option.
To go end of the file: press ESC
1) type capital G (Capital G)
2) press shift + g (small g)
To go top of the file there are the following ways: press ESC
1) press 1G (Capital G)
2) press gg (small g) or 1gg
3) You can jump to the particular line number,e.g wanted to go 1 line number, press 1 + G
from itertools import repeat, starmap
results = list(starmap(do, repeat((), 3)))
See the repeatfunc recipe from the itertools module that is actually much more powerful. If you need to just call the method but don't care about the return values you can use it in a for loop:
for _ in starmap(do, repeat((), 3)): pass
but that's getting ugly.
One alternative is to represent your 2D array as a 1D array. This can make element-wise operations more efficient. You should probably wrap it in a class that would also contain width and height.
Another alternative is to represent a 2D array as an std::vector<std::vector<int> >
. This will let you use STL's algorithms for array arithmetic, and the vector will also take care of memory management for you.
I don't know any native cmdlet in powershell but you can use com object instead:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()
you can create a powershell script save as set-shortcut.ps1 in your $pwd
param ( [string]$SourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()
and call it like this
Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"
If you want to pass arguments to the target exe, it can be done by:
#Set the additional parameters for the shortcut
$Shortcut.Arguments = "/argument=value"
before $Shortcut.Save().
For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.
param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()
For those who still have this problem (for example to switch from 2.8.0 to 2.10.0), move to the file gradle-wrapper.properties and set distributionUrl like that.
distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
I changed 2.8.0 to 2.10.0 and don't forget to Sync after
You can use AndroidAccessors
Plugin of Android Studio
to generate getter and setter without m as prefix to methods
Ex: mId;
Will generate getId()
and setId()
instead of getmId()
and setmId()
You could type "prop" and then press tab twice. That will generate the following.
public TYPE Type { get; set; }
Then you change "TYPE" and "Type":
public string myString {get; set;}
You can also get the full property typing "propfull" and then tab twice. That would generate the field and the full property.
private int myVar;
public int MyProperty
{
get { return myVar;}
set { myVar = value;}
}
You can't close a current window or any window or page that is opened using '_self' But you can do this
var customWindow = window.open('', '_blank', '');
customWindow.close();
For single line comment you can use Ctrl + / and for multiple line comment you can use Ctrl + Shift + / after selecting the lines you want to comment in java editor.
On Mac/OS X you can use ? + / to comment out single lines or selected blocks.
You have to set the 'float mode' to fixed.
float num = 15.839;
// this will output 15.84
std::cout << std::fixed << "num = " << std::setprecision(2) << num << std::endl;
On Windows Powershell:
Get-PSDrive
[System.IO.DriveInfo]::getdrives()
wmic diskdrive
wmic volume
Also the utility dskwipe: http://smithii.com/dskwipe
dskwipe.exe -l
UPDATE: The image size Must be larger than (600 x 315px)
The image size can be any size because Faceboook re-size the image width & height.
The default height is 208px
& width is 398px
for a post permalink:
www.facebook.com/{username}/posts/{post_id}
But for a timeline view:
www.facebook.com/{username}
width is 377px
& height is 197px
I hope this will help you!
One very small nit to pick:
The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:
"john@work"@myemployer.com
This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:
SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1
More information:
Heres a few methods that convert an array of bytes to a string. I've tested them they work well.
public String getStringFromByteArray(byte[] settingsData) {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(settingsData);
Reader reader = new BufferedReader(new InputStreamReader(byteArrayInputStream));
StringBuilder sb = new StringBuilder();
int byteChar;
try {
while((byteChar = reader.read()) != -1) {
sb.append((char) byteChar);
}
}
catch(IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public String getStringFromByteArray(byte[] settingsData) {
StringBuilder sb = new StringBuilder();
for(byte willBeChar: settingsData) {
sb.append((char) willBeChar);
}
return sb.toString();
}
All the answers here seem to be around service and factory, and that's valid since that was what was being asked about. But it's also important to keep in mind that there are several others including provider()
, value()
, and constant()
.
The key to remember is that each one is a special case of the other. Each special case down the chain allowing you to do the same thing with less code. Each one also having some additional limitation.
To decide when to use which you just see which one allows you to do what you want in less code. Here is an image illustrating just how similar they are:
For a complete step by step breakdown and quick reference of when to use each you can visit the blog post where I got this image from:
Günter Zöchbauer's answer is the right one. Just consider adding the following line:
showImageBrowseDlg() {
// from http://stackoverflow.com/a/32010791/217408
let event = new MouseEvent('click', {bubbles: true});
event.stopPropagation();
this.renderer.invokeElementMethod(
this.fileInput.nativeElement, 'dispatchEvent', [event]);
}
In my case I would get a "caught RangeError: Maximum call stack size exceeded" error if not. (I have a div card firing on click and the input file inside)
Sometimes we have more than one net interface.
A simple method to find out the mac address of a specific interface, is:
def getmac(interface):
try:
mac = open('/sys/class/net/'+interface+'/address').readline()
except:
mac = "00:00:00:00:00:00"
return mac[0:17]
to call the method is simple
myMAC = getmac("wlan0")
For some reason, import as suggested by Ricardo didnt work for me. I got it working with following statement:
<import resource="classpath*:/spring-config.xml" />
Performance-wise, I found the ServiceStack's serializer a bit faster than then others. It's JsonSerializer class in ServiceStack.Text namespace.
https://github.com/ServiceStack/ServiceStack.Text
ServiceStack is available through NuGet package: https://www.nuget.org/packages/ServiceStack/
You could use a negative look-ahead assertion:
^(?!tbd_).+
Or a negative look-behind assertion:
(^.{1,3}$|^.{4}(?<!tbd_).*)
Or just plain old character sets and alternations:
^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*
For production code requiring a large compatibility with client browsers I still suggest Ivan Nevostruev's answer above with shim to ensure Object.keys
in older browsers. However, it's possible to get the exact functionality requested using ECMA's new defineProperty
feature.
As of ECMAScript 5 - Object.defineProperty
As of ECMA5 you can use Object.defineProperty()
to define non-enumerable properties. The current compatibility still has much to be desired, but this should eventually become usable in all browsers. (Specifically note the current incompatibility with IE8!)
Object.defineProperty(Object.prototype, 'keys', {
value: function keys() {
var keys = [];
for(var i in this) if (this.hasOwnProperty(i)) {
keys.push(i);
}
return keys;
},
enumerable: false
});
var o = {
'a': 1,
'b': 2
}
for (var k in o) {
console.log(k, o[k])
}
console.log(o.keys())
# OUTPUT
# > a 1
# > b 2
# > ["a", "b"]
However, since ECMA5 already added Object.keys
you might as well use:
Object.defineProperty(Object.prototype, 'keys', {
value: function keys() {
return Object.keys(this);
},
enumerable: false
});
Original answer
Object.prototype.keys = function ()
{
var keys = [];
for(var i in this) if (this.hasOwnProperty(i))
{
keys.push(i);
}
return keys;
}
Edit: Since this answer has been around for a while I'll leave the above untouched. Anyone reading this should also read Ivan Nevostruev's answer below.
There's no way of making prototype functions non-enumerable which leads to them always turning up in for-in loops that don't use hasOwnProperty
. I still think this answer would be ideal if extending the prototype of Object wasn't so messy.
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
I hope this will help somebody, I solved the problem like this
There was a problem because the database was not open. Command startup opens the database.
This you can solve with command alter database open
in some case with alter database open resetlogs
$ sqlplus / sysdba
SQL> startup
ORACLE instance started.
Total System Global Area 1073741824 bytes
Fixed Size 8628936 bytes
Variable Size 624952632 bytes
Database Buffers 436207616 bytes
Redo Buffers 3952640 bytes
Database mounted.
Database opened.
SQL> conn user/pass123
Connected.
Yes, if your Column annotation has the runtime retention
@Retention(RetentionPolicy.RUNTIME)
@interface Column {
....
}
you can do something like this
for (Field f: MyClass.class.getFields()) {
Column column = f.getAnnotation(Column.class);
if (column != null)
System.out.println(column.columnName());
}
UPDATE : To get private fields use
Myclass.class.getDeclaredFields()
Ugly, (and doesn't use your method call above) but works:
echo 'First day of the month: ' . date('m/d/y h:i a',(strtotime('this month',strtotime(date('m/01/y')))));
Go to your tsconfig.json
file and change "noImplicitReturns": false
then add "strictPropertyInitialization": false
to your tsconfig.json
file under "compilerOptions"
property. Here is what my tsconfig.json
file looks like
tsconfig.json
{
...
"compilerOptions": {
....
"noImplicitReturns": false,
....
"strictPropertyInitialization": false
},
"angularCompilerOptions": {
......
}
}
Hope this will help !! Good Luck
<div id="412412412" class="input-group date">
<div class="input-group-prepend">
<button class="btn btn-danger" type="button">Button Click</button>
<input type="text" class="form-control" value="">
</div>
</div>
In my situation, i use this code:
$(this).parent().closest('.date').attr('id')
Hope this help someone.
int month = Convert.ToInt32(ddlMonth.SelectedValue);/*Store month Value From page*/
int year = Convert.ToInt32(txtYear.Value);/*Store Year Value From page*/
int days = System.DateTime.DaysInMonth(year, month); /*this will store no. of days for month, year that we store*/
I up voted slckin's answer. My problem was that I was thoughtful and added double quotes around the paths. I removed the double quotes in all of the three variables: PYTHONHOME, PYTHONPATH, and PATH. Note that this was in a cmd or bat file to setup the environment for other tools. However, the double quotes may be useful in an icon setting. Typing
set
revealed that the quotes where in the path and not dropped as expected. I also shorted the PATH so that it was less than 256 characters long.
The task can be solved using the following piece of code, [0:28] being interval where the name is being held, while [29:34] contains the actual pid.
import os
program_pid = 0
program_name = "notepad.exe"
task_manager_lines = os.popen("tasklist").readlines()
for line in task_manager_lines:
try:
if str(line[0:28]) == program_name + (28 - len(program_name) * ' ': #so it includes the whitespaces
program_pid = int(line[29:34])
break
except:
pass
print(program_pid)
It can also be due to a duplicate entry in any of the tables that are used.
In chrome,simply tick "Desktop site" and then remove tick!!
You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType
value. If I have two rows with the same FruitType
value but different Fruit_Id
values for example, what should the system do?
Select Min(tblFruit_id) As tblFruit_id
, tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType
You can use a regular expression to test for a match and capture the first two digits:
import re
for i in range(1000):
match = re.match(r'(1[56])', str(i))
if match:
print(i, 'begins with', match.group(1))
The regular expression (1[56])
matches a 1 followed by either a 5 or a 6 and stores the result in the first capturing group.
Output:
15 begins with 15
16 begins with 16
150 begins with 15
151 begins with 15
152 begins with 15
153 begins with 15
154 begins with 15
155 begins with 15
156 begins with 15
157 begins with 15
158 begins with 15
159 begins with 15
160 begins with 16
161 begins with 16
162 begins with 16
163 begins with 16
164 begins with 16
165 begins with 16
166 begins with 16
167 begins with 16
168 begins with 16
169 begins with 16
What about an onclick function:
<form id="form">
<input type="text" name="firstInput">
<button type="button" name="namebutton"
onClick="$('#gif').css('visibility', 'visible');
$('#form').submit();">
</form>
Of course you can put this in a function and then trigger it with an onClick
the first parameters of function JSON.parse
should be a String, and your data is a JavaScript object, so it will convert to a String [object object]
, you should use JSON.stringify
before pass the data
JSON.parse(JSON.stringify(userData))
Using UIPickerview is the right way to go to implement it according to Apple's Human Interface Guidelines
If you select drop down in mobile safari it will show UIPickerview to let the use choose drop down items.
Alternatively
you can use UIPopoverController till iOS 9 as its deprecated but its better to stick with UIModalPresentationPopover of view you want o show as well
you can use UIActionsheet to show the items but it's better to use UIAlertViewController and choose UIActionSheetstyle to show as the former is deprecated in latest versions
Apart from HTML 5 data-tip You can use css also for making a totally customizable tooltip to be used anywhere throughout your markup.
/* ToolTip classses */ _x000D_
.tooltip {_x000D_
display: inline-block; _x000D_
}_x000D_
.tooltip .tooltiptext {_x000D_
margin-left:9px;_x000D_
width : 320px;_x000D_
visibility: hidden;_x000D_
background-color: #FFF;_x000D_
border-radius:4px;_x000D_
border: 1px solid #aeaeae;_x000D_
position: absolute;_x000D_
z-index: 1;_x000D_
padding: 5px;_x000D_
margin-top : -15px; _x000D_
opacity: 0;_x000D_
transition: opacity 0.5s;_x000D_
}_x000D_
.tooltip .tooltiptext::after {_x000D_
content: " ";_x000D_
position: absolute;_x000D_
top: 5%;_x000D_
right: 100%; _x000D_
margin-top: -5px;_x000D_
border-width: 5px;_x000D_
border-style: solid;_x000D_
border-color: transparent #aeaeae transparent transparent;_x000D_
}_x000D_
_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
}
_x000D_
<div class="tooltip">_x000D_
<input type="text" />_x000D_
<span class="tooltiptext">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </span>_x000D_
</div>
_x000D_
This worked for me in Firefox and Chrome and IE8...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style type="text/css">
div.section:hover div.image, div.section:hover div.layer {
border: solid 1px red;
}
</style>
</head>
<body>
<div class="section">
<div class="image"><img src="myImage.jpg" /></div>
<div class="layer">Lorem Ipsum</div>
</div>
</body>
</html>
... you may want to test this with IE6 as well (I'm not sure if it'll work there).
You would expect that this is easily possible but that seems not be the case. The only way I see at the moment is to create a user defined JQL function. I never tried this but here is a plug-in:
http://confluence.atlassian.com/display/DEVNET/Plugin+Tutorial+-+Adding+a+JQL+Function+to+JIRA
As the error message is trying very hard to tell you, you can't deserialize a single object into a collection (List<>
).
You want to deserialize into a single RootObject
.
This is useful when you want to compare data that correspond to different units. In that case, you want to remove the units. To do that in a consistent way of all the data, you transform the data in a way that the variance is unitary and that the mean of the series is 0.
In the manual for GNU make, they talk about this specific example when describing the value
function:
The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.
The syntax of the value function is:
$(value variable)
Note that variable is the name of a variable; not a reference to that variable. Therefore you would not normally use a ‘$’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)
The result of this function is a string containing the value of variable, without any expansion occurring. For example, in this makefile:
FOO = $PATH all: @echo $(FOO) @echo $(value FOO)
The first output line would be ATH, since the “$P” would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.
Yes, some how the ajax call aborted. The cause may be following.
ls -i file #output is for me 68551981
debugfs -R 'stat <68551981>' /dev/sda3 # /dev/sda3 is the disk on which the file exists
#results - crtime value
[root@loft9156 ~]# debugfs -R 'stat <68551981>' /dev/sda3
debugfs 1.41.12 (17-May-2010)
Inode: 68551981 Type: regular Mode: 0644 Flags: 0x80000
Generation: 769802755 Version: 0x00000000:00000001
User: 0 Group: 0 Size: 38973440
File ACL: 0 Directory ACL: 0
Links: 1 Blockcount: 76128
Fragment: Address: 0 Number: 0 Size: 0
ctime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013
atime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013
mtime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013
**crtime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013**
Size of extra inode fields: 28
EXTENTS:
(0-511): 352633728-352634239, (512-1023): 352634368-352634879, (1024-2047): 288392192-288393215, (2048-4095): 355803136-355805183, (4096-6143): 357941248-357943295, (6144
-9514): 357961728-357965098
For python version 2.x you can simply use
pip install pillow
But for python version 3.X you need to specify
(sudo) pip3 install pillow
when you enter pip in bash hit tab and you will see what options you have
You can use the git-credential-store via
git config credential.helper store
which stores your password unencrypted in the file system:
Using this helper will store your passwords unencrypted on disk, protected only by filesystem permissions. If this is not an acceptable security tradeoff, try git-credential-cache, or find a helper that integrates with secure storage provided by your operating system.
Use the git-credential-cache which by default stores the password for 15 minutes.
git config credential.helper cache
to set a different timeout, use --timeout
(here 5 minutes)
git config credential.helper 'cache --timeout=300'
- If you’re using a Mac, Git comes with an “osxkeychain” mode, which caches credentials in the secure keychain that’s attached to your system account. This method stores the credentials on disk, and they never expire, but they’re encrypted with the same system that stores HTTPS certificates and Safari auto-fills. Running the following on the command line will enable this feature:
git config --global credential.helper osxkeychain
. You'll need to store the credentials in the Keychain using the Keychain app as well.- If you’re using Windows, you can install a helper called “Git Credential Manager for Windows.” This is similar to the “osxkeychain” helper described above, but uses the Windows Credential Store to control sensitive information. It can be found at https://github.com/Microsoft/Git-Credential-Manager-for-Windows. [emphases mine]
You should not encrypt passwords, instead you should hash them using an algorithm like bcrypt. This answer explains how to properly implement password hashing in PHP. Still, here is how you would encrypt/decrypt:
$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces
To Encrypt:
$iv = mcrypt_create_iv(
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
MCRYPT_DEV_URANDOM
);
$encrypted = base64_encode(
$iv .
mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
$string,
MCRYPT_MODE_CBC,
$iv
)
);
To Decrypt:
$data = base64_decode($encrypted);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
$decrypted = rtrim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),
MCRYPT_MODE_CBC,
$iv
),
"\0"
);
Warning: The above example encrypts information, but it does not authenticate the ciphertext to prevent tampering. You should not rely on unauthenticated encryption for security, especially since the code as provided is vulnerable to padding oracle attacks.
See also:
Also, don't just use a "password" for an encryption key. Encryption keys are random strings.
echo 'Encrypted:' . "\n";
var_dump($encrypted); // "m1DSXVlAKJnLm7k3WrVd51omGL/05JJrPluBonO9W+9ohkNuw8rWdJW6NeLNc688="
echo "\n";
echo 'Decrypted:' . "\n";
var_dump($decrypted); // " string to be encrypted "
If you are using TOAD, you will need to download the 32-bit version of the Oracle Client Tools.
Since the Client Tools are different on a per-processor architecture basis, you probably need to install versions.
Not knowing time cost of shared_copy copy operation where atomic increment and decrement is in, I suffered from much higher CPU usage problem. I never expected atomic increment and decrement may take so much cost.
Following my test result, int32 atomic increment and decrement takes 2 or 40 times than non-atomic increment and decrement. I got it on 3GHz Core i7 with Windows 8.1. The former result comes out when no contention occurs, the latter when high possibility of contention occurs. I keep in mind that atomic operations are at last hardware based lock. Lock is lock. Bad to performance when contention occurs.
Experiencing this, I always use byref(const shared_ptr&) than byval(shared_ptr).
%USERNAME%
is the correct answer in batch and other in Windows environments.
Another option is to use %USERPROFILE%
to get the user's path, like C:\Users\username
.
Set LDFLAGS and CFLAGS when you run make:
$ LDFLAGS="-L/home/me/local/lib" CFLAGS="-I/home/me/local/include" make
If you don't want to do that a gazillion times, export these in your .bashrc (or your shell equivalent). Also set LD_LIBRARY_PATH to include /home/me/local/lib:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/me/local/lib
Please bear in mind that 2 empty stdClasses are not strictly equal. This is very important when writing mockery expectations.
php > $a = new stdClass();
php > $b = new stdClass();
php > var_dump($a === $b);
bool(false)
php > var_dump($a == $b);
bool(true)
php > var_dump($a);
object(stdClass)#1 (0) {
}
php > var_dump($b);
object(stdClass)#2 (0) {
}
php >
I solved the problem by install Git Bash from Download Git Bash.
Setting this option 3 when installing the software as shown bellow.
Finally select the project folder by right click using Bash as shown below.
and type
npm install
. It works for me.
use a Relativelayout to wrap LinearLayout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:round="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text="<"/>
<TextView
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:layout_weight = "1"/>
<Button
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text=">"/>
</LinearLayout>
</RelativeLayout>`
I think the same places of them are: all of them can change the this value of a function.The differences of them are: the bind function will return a new function as a result; the call and apply methods will execute the function immediately, but apply can accept a array as params,and it will parse the array separated.And also, the bind function can be Currying.
Short answer: Use the change
event. Here's a couple of practical examples. Since I misread the question, I'll include jQuery examples along with plain JavaScript. You're not gaining much, if anything, by using jQuery though.
Using querySelector
.
var checkbox = document.querySelector("input[name=checkbox]");
checkbox.addEventListener('change', function() {
if (this.checked) {
console.log("Checkbox is checked..");
} else {
console.log("Checkbox is not checked..");
}
});
_x000D_
<input type="checkbox" name="checkbox" />
_x000D_
$('input[name=checkbox]').change(function() {
if ($(this).is(':checked')) {
console.log("Checkbox is checked..")
} else {
console.log("Checkbox is not checked..")
}
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" />
_x000D_
Here's an example of a list of checkboxes. To select multiple elements we use querySelectorAll
instead of querySelector
. Then use Array.filter
and Array.map
to extract checked values.
// Select all checkboxes with the name 'settings' using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]");
let enabledSettings = []
/*
For IE11 support, replace arrow functions with normal functions and
use a polyfill for Array.forEach:
https://vanillajstoolkit.com/polyfills/arrayforeach/
*/
// Use Array.forEach to add an event listener to each checkbox.
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
enabledSettings =
Array.from(checkboxes) // Convert checkboxes to an array to use filter and map.
.filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.
.map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects.
console.log(enabledSettings)
})
});
_x000D_
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
_x000D_
let checkboxes = $("input[type=checkbox][name=settings]")
let enabledSettings = [];
// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
enabledSettings = checkboxes
.filter(":checked") // Filter out unchecked boxes.
.map(function() { // Extract values using jQuery map.
return this.value;
})
.get() // Get array.
console.log(enabledSettings);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
_x000D_
To avoid some of the problems mentioned above (not robust for nulls etc etc), to get first and last element in a list an approach could be
import java.util.List;
public static final <A> A getLastElement(List<A> list) {
return list != null ? getElement(list, list.size() - 1) : null;
}
public static final <A> A getFirstElement(List<A> list) {
return list != null ? getElement(list, 0) : null;
}
private static final <A> A getElement(List<A> list, int pointer) {
A res = null;
if (list.size() > 0) {
res = list.get(pointer);
}
return res;
}
The convention adopted is that the first/last element of an empty list is null...
I am using entity framework with LINQ. Following code was helpful for me;
1- For multiple records
using (var dbContext = new Chat_ServerEntities())
{
var allRec= dbContext.myEntities;
dbContext.myEntities.RemoveRange(allRec);
dbContext.SaveChanges();
}
2- For Single record
using (var dbContext = new Chat_ServerEntities())
{
var singleRec = dbContext.ChatUserConnections.FirstOrDefault( x => x.ID ==1);// object your want to delete
dbContext.ChatUserConnections.Remove(singleRec);
dbContext.SaveChanges();
}
I was able to get this to work. I will describe my application and the integration test here.
The Example Application
The example application has two classes and one interface that are relevant to this problem:
These classes and the repository interface are described in the following.
The source code of the PersistenceContext
class looks as follows:
import com.jolbox.bonecp.BoneCPDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "net.petrikainulainen.spring.datajpa.todo.repository")
@PropertySource("classpath:application.properties")
public class PersistenceContext {
protected static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
protected static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
protected static final String PROPERTY_NAME_DATABASE_URL = "db.url";
protected static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_PACKAGES_TO_SCAN = "net.petrikainulainen.spring.datajpa.todo.model";
@Autowired
private Environment environment;
@Bean
public DataSource dataSource() {
BoneCPDataSource dataSource = new BoneCPDataSource();
dataSource.setDriverClass(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setJdbcUrl(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN);
Properties jpaProperties = new Properties();
jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
jpaProperties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
}
Let's assume that we have a simple entity called Todo
which source code looks as follows:
@Entity
@Table(name="todos")
public class Todo {
public static final int MAX_LENGTH_DESCRIPTION = 500;
public static final int MAX_LENGTH_TITLE = 100;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "description", nullable = true, length = MAX_LENGTH_DESCRIPTION)
private String description;
@Column(name = "title", nullable = false, length = MAX_LENGTH_TITLE)
private String title;
@Version
private long version;
}
Our repository interface has a single method called updateTitle()
which updates the title of a todo entry. The source code of the TodoRepository
interface looks as follows:
import net.petrikainulainen.spring.datajpa.todo.model.Todo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface TodoRepository extends JpaRepository<Todo, Long> {
@Modifying
@Query("Update Todo t SET t.title=:title WHERE t.id=:id")
public void updateTitle(@Param("id") Long id, @Param("title") String title);
}
The updateTitle()
method is not annotated with the @Transactional
annotation because I think that it is best to use a service layer as a transaction boundary.
The Integration Test
The Integration Test uses DbUnit, Spring Test and Spring-Test-DBUnit. It has three components which are relevant to this problem:
These components are described with more details in the following.
The name of the DbUnit dataset file which is used to initialize the database to known state is toDoData.xml and its content looks as follows:
<dataset>
<todos id="1" description="Lorem ipsum" title="Foo" version="0"/>
<todos id="2" description="Lorem ipsum" title="Bar" version="0"/>
</dataset>
The name of the DbUnit dataset which is used to verify that the title of the todo entry is updated is called toDoData-update.xml and its content looks as follows (for some reason the version of the todo entry was not updated but the title was. Any ideas why?):
<dataset>
<todos id="1" description="Lorem ipsum" title="FooBar" version="0"/>
<todos id="2" description="Lorem ipsum" title="Bar" version="0"/>
</dataset>
The source code of the actual integration test looks as follows (Remember to annotate the test method with the @Transactional
annotation):
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceContext.class})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class })
@DatabaseSetup("todoData.xml")
public class ITTodoRepositoryTest {
@Autowired
private TodoRepository repository;
@Test
@Transactional
@ExpectedDatabase("toDoData-update.xml")
public void updateTitle_ShouldUpdateTitle() {
repository.updateTitle(1L, "FooBar");
}
}
After I run the integration test, the test passes and the title of the todo entry is updated. The only problem which I am having is that the version field is not updated. Any ideas why?
I undestand that this description is a bit vague. If you want to get more information about writing integration tests for Spring Data JPA repositories, you can read my blog post about it.
Well, wait a minute. I don't think the base tag deserves this bad reputation.
The nice thing about the base tag is that it enables you to do complex URL rewrites with less hassle.
Here's an example. You decide to move http://example.com/product/category/thisproduct to http://example.com/product/thisproduct. You change your .htaccess file to rewrite the first URL to the second URL.
With the base tag in place, you do your .htaccess rewrite and that's it. No problem. But without the base tag, all of your relative links will break.
URL rewrites are often necessary, because tweaking them can help your site's architecture and search engine visibility. True, you'll need workarounds for the "#" and '' problems that folks mentioned. But the base tag deserves a place in the toolkit.
I've done this before. You can just create a new exception and grab the stack trace on it without throwing it, then examine the stack trace. As the other answer says though, it's extremely costly--don't do it in a tight loop.
I've done it before for a logging utility on an app where performance didn't matter much (Performance rarely matters much at all, actually--as long as you display the result to an action such as a button click quickly).
It was before you could get the stack trace, exceptions just had .printStackTrace() so I had to redirect System.out to a stream of my own creation, then (new Exception()).printStackTrace(); Redirect System.out back and parse the stream. Fun stuff.
If there are multiple values for the same key, the following code will append those values to a list corresponding to their key,
d = dict()
for x,y in t:
if(d.has_key(y)):
d[y].append(x)
else:
d[y] = [x]
I have no comment on the concatenation itself, but I'd like to point out that @Jakub Hampl's suggestion:
For building strings in the DOM, in some cases it might be better to iteratively add to the DOM, rather then add a huge string at once.
is wrong, because it's based on a flawed test. That test never actually appends into the DOM.
This fixed test shows that creating the string all at once before rendering it is much, MUCH faster. It's not even a contest.
(Sorry this is a separate answer, but I don't have enough rep to comment on answers yet.)
Just cast one to int and then cast it to the other enum (considering that you want the mapping done based on value):
Gender2 gender2 = (Gender2)((int)gender1);
You can use .offset()
to get the offset compared to the document
element and then use the scrollTop
property of the window
element to find how far down the page the user has scrolled:
var scrollTop = $(window).scrollTop(),
elementOffset = $('#my-element').offset().top,
distance = (elementOffset - scrollTop);
The distance
variable now holds the distance from the top of the #my-element
element and the top-fold.
Here is a demo: http://jsfiddle.net/Rxs2m/
Note that negative values mean that the element is above the top-fold.
you may also go for a simple View.OnClickListener
:
satView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(((CompoundButton) view).isChecked()){
System.out.println("Checked");
} else {
System.out.println("Un-Checked");
}
}
});
As the rank doesn't depend at all from the contacts
RANKED_RSLTS
QRY_ID | RES_ID | SCORE | RANK
-------------------------------------
A | 1 | 15 | 3
A | 2 | 32 | 1
A | 3 | 29 | 2
C | 7 | 61 | 1
C | 9 | 30 | 2
Thus :
SELECT
C.*
,R.SCORE
,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT *,
MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
FROM RSLTS) R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID
One way to center any element of unknown height and width both horizontally and vertically:
table {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Alternatively, use a flex container:
.parent-element {
display: flex;
justify-content: center;
align-items: center;
}
Wouldn't you just change:
numero = stmt.executeUpdate(query);
to:
numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
Take a look at the documentation for the JDBC Statement
interface.
Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero
variable is completely irrelevant and its value is never read after it is set.
From the MySQL manual
INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas. Example:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
add it in your index.php file, and it will work on all over your site
if ( function_exists( 'date_default_timezone_set' ) ) {
date_default_timezone_set('Asia/Kolkata');
}
foo module in python would be the equivalent to a Foo class file in Java
or
foobar module in python would be the equivalent to a FooBar class file in Java
There is a new possible error for this one related to the latest Android Wear technology. I was trying to get an emulator started for the wear SDK in preparation for next week. The API level only supports it in the latest build of 4.4.2 KitKat.
So if you are using something such as the wearable, it starts the default off still in Eclipse as 2.3.3 Gingerbread. Be sure that your target matches the lowest possible supported target. For the wearables its the latest 19 KitKat.
you can try this...
db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");
There is no need of creating a directive especially just to have a ng-repeat
complete event.
ng-init
does the magic for you.
<div ng-repeat="thing in things" ng-init="$last && finished()">
the $last
makes sure, that finished
only gets fired, when the last element has been rendered to the DOM.
Do not forget to create $scope.finished
event.
Happy Coding!!
EDIT: 23 Oct 2016
In case you also want to call the finished
function when there is no item in the array then you may use the following workaround
<div style="display:none" ng-init="things.length < 1 && finished()"></div>
//or
<div ng-if="things.length > 0" ng-init="finished()"></div>
Just add the above line on the top of the ng-repeat
element. It will check if the array is not having any value and call the function accordingly.
E.g.
<div ng-if="things.length > 0" ng-init="finished()"></div>
<div ng-repeat="thing in things" ng-init="$last && finished()">
if you have a checkbox and you would like to fetch it's value ie true / false in any java file--
Use--
Context mContext;
boolean checkFlag;
checkFlag=PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(KEY,DEFAULT_VALUE);`
By this way You can convert char to int and int to char easily:
int charToInt(char c)
{
int arr[]={0,1,2,3,4,5,6,7,8,9};
return arr[c-'0'];
}
I've given up trying to align my text on buttons! Now, if I need it, I'm using <a>
tags, like so:
<a href="javascript:void();" style="display:block;font-size:1em;padding:5px;cursor:default;" onclick="document.getElementById('form').submit();">Submit</a>
So, if the document's font size is 12px, my "button" will have 22px height. And the text will be vertically align. That in theory, because, in some casses, an unequal padding of "6px 5px 4px 5px" will do the job done.
Although, is a hack, this technique is pretty good for solving compatibility issues in older browsers too, like IE6!
s.index(x[, i[, j]])
index of the first occurrence of x in s (at or after index i and before index j)
If you have perl installed, then perl -i -n -e"print unless m{(ERROR|REFERENCE)}"
should do the trick.
For user configuration I've noticed a tendency towards moving away from individual ~/.myprogramrc
to a structure below ~/.config
. For example, Qt 4 uses ~/.config/<vendor>/<programname>
with the default settings of QSettings
. The major desktop environments KDE and Gnome use a file structure below a specific folder too (not sure if KDE 4 uses ~/.config
, XFCE does use ~/.config
).
I'm getting an error in the IF conditional. What am I doing wrong?
There reason that you get a SyntaxError
is that there is no &&
operator in Python. Likewise ||
and !
are not valid Python operators.
Some of the operators you may know from other languages have a different name in Python.
The logical operators &&
and ||
are actually called and
and or
.
Likewise the logical negation operator !
is called not
.
So you could just write:
if len(a) % 2 == 0 and len(b) % 2 == 0:
or even:
if not (len(a) % 2 or len(b) % 2):
I summarized the operator "equivalents" in this table:
+------------------------------+---------------------+
| Operator (other languages) | Operator (Python) |
+==============================+=====================+
| && | and |
+------------------------------+---------------------+
| || | or |
+------------------------------+---------------------+
| ! | not |
+------------------------------+---------------------+
See also Python documentation: 6.11. Boolean operations.
Besides the logical operators Python also has bitwise/binary operators:
+--------------------+--------------------+
| Logical operator | Bitwise operator |
+====================+====================+
| and | & |
+--------------------+--------------------+
| or | | |
+--------------------+--------------------+
There is no bitwise negation in Python (just the bitwise inverse operator ~
- but that is not equivalent to not
).
See also 6.6. Unary arithmetic and bitwise/binary operations and 6.7. Binary arithmetic operations.
The logical operators (like in many other languages) have the advantage that these are short-circuited. That means if the first operand already defines the result, then the second operator isn't evaluated at all.
To show this I use a function that simply takes a value, prints it and returns it again. This is handy to see what is actually evaluated because of the print statements:
>>> def print_and_return(value):
... print(value)
... return value
>>> res = print_and_return(False) and print_and_return(True)
False
As you can see only one print statement is executed, so Python really didn't even look at the right operand.
This is not the case for the binary operators. Those always evaluate both operands:
>>> res = print_and_return(False) & print_and_return(True);
False
True
But if the first operand isn't enough then, of course, the second operator is evaluated:
>>> res = print_and_return(True) and print_and_return(False);
True
False
To summarize this here is another Table:
+-----------------+-------------------------+
| Expression | Right side evaluated? |
+=================+=========================+
| `True` and ... | Yes |
+-----------------+-------------------------+
| `False` and ... | No |
+-----------------+-------------------------+
| `True` or ... | No |
+-----------------+-------------------------+
| `False` or ... | Yes |
+-----------------+-------------------------+
The True
and False
represent what bool(left-hand-side)
returns, they don't have to be True
or False
, they just need to return True
or False
when bool
is called on them (1).
So in Pseudo-Code(!) the and
and or
functions work like these:
def and(expr1, expr2):
left = evaluate(expr1)
if bool(left):
return evaluate(expr2)
else:
return left
def or(expr1, expr2):
left = evaluate(expr1)
if bool(left):
return left
else:
return evaluate(expr2)
Note that this is pseudo-code not Python code. In Python you cannot create functions called and
or or
because these are keywords.
Also you should never use "evaluate" or if bool(...)
.
This implicit bool
call can be used to customize how your classes behave with and
, or
and not
.
To show how this can be customized I use this class which again print
s something to track what is happening:
class Test(object):
def __init__(self, value):
self.value = value
def __bool__(self):
print('__bool__ called on {!r}'.format(self))
return bool(self.value)
__nonzero__ = __bool__ # Python 2 compatibility
def __repr__(self):
return "{self.__class__.__name__}({self.value})".format(self=self)
So let's see what happens with that class in combination with these operators:
>>> if Test(True) and Test(False):
... pass
__bool__ called on Test(True)
__bool__ called on Test(False)
>>> if Test(False) or Test(False):
... pass
__bool__ called on Test(False)
__bool__ called on Test(False)
>>> if not Test(True):
... pass
__bool__ called on Test(True)
If you don't have a __bool__
method then Python also checks if the object has a __len__
method and if it returns a value greater than zero.
That might be useful to know in case you create a sequence container.
See also 4.1. Truth Value Testing.
Probably a bit beyond the scope of the original question but in case you're dealing with NumPy arrays or subclasses (like Pandas Series or DataFrames) then the implicit bool
call
will raise the dreaded ValueError
:
>>> import numpy as np
>>> arr = np.array([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> import pandas as pd
>>> s = pd.Series([1,2,3])
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> s and s
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
In these cases you can use the logical and function from NumPy which performs an element-wise and
(or or
):
>>> np.logical_and(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([False, False, True, False])
>>> np.logical_or(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([ True, False, True, True])
If you're dealing just with boolean arrays you could also use the binary operators with NumPy, these do perform element-wise (but also binary) comparisons:
>>> np.array([False,False,True,True]) & np.array([True, False, True, False])
array([False, False, True, False])
>>> np.array([False,False,True,True]) | np.array([True, False, True, False])
array([ True, False, True, True])
(1)
That the bool
call on the operands has to return True
or False
isn't completely correct. It's just the first operand that needs to return a boolean in it's __bool__
method:
class Test(object):
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value
__nonzero__ = __bool__ # Python 2 compatibility
def __repr__(self):
return "{self.__class__.__name__}({self.value})".format(self=self)
>>> x = Test(10) and Test(10)
TypeError: __bool__ should return bool, returned int
>>> x1 = Test(True) and Test(10)
>>> x2 = Test(False) and Test(10)
That's because and
actually returns the first operand if the first operand evaluates to False
and if it evaluates to True
then it returns the second operand:
>>> x1
Test(10)
>>> x2
Test(False)
Similarly for or
but just the other way around:
>>> Test(True) or Test(10)
Test(True)
>>> Test(False) or Test(10)
Test(10)
However if you use them in an if
statement the if
will also implicitly call bool
on the result. So these finer points may not be relevant for you.
If you are a windows user and using python 3, then this post will help you to do parallel programming in python.when you run a usual multiprocessing library's pool programming, you will get an error regarding the main function in your program. This is because the fact that windows has no fork() functionality. The below post is giving a solution to the mentioned problem .
http://python.6.x6.nabble.com/Multiprocessing-Pool-woes-td5047050.html
Since I was using the python 3, I changed the program a little like this:
from types import FunctionType
import marshal
def _applicable(*args, **kwargs):
name = kwargs['__pw_name']
code = marshal.loads(kwargs['__pw_code'])
gbls = globals() #gbls = marshal.loads(kwargs['__pw_gbls'])
defs = marshal.loads(kwargs['__pw_defs'])
clsr = marshal.loads(kwargs['__pw_clsr'])
fdct = marshal.loads(kwargs['__pw_fdct'])
func = FunctionType(code, gbls, name, defs, clsr)
func.fdct = fdct
del kwargs['__pw_name']
del kwargs['__pw_code']
del kwargs['__pw_defs']
del kwargs['__pw_clsr']
del kwargs['__pw_fdct']
return func(*args, **kwargs)
def make_applicable(f, *args, **kwargs):
if not isinstance(f, FunctionType): raise ValueError('argument must be a function')
kwargs['__pw_name'] = f.__name__ # edited
kwargs['__pw_code'] = marshal.dumps(f.__code__) # edited
kwargs['__pw_defs'] = marshal.dumps(f.__defaults__) # edited
kwargs['__pw_clsr'] = marshal.dumps(f.__closure__) # edited
kwargs['__pw_fdct'] = marshal.dumps(f.__dict__) # edited
return _applicable, args, kwargs
def _mappable(x):
x,name,code,defs,clsr,fdct = x
code = marshal.loads(code)
gbls = globals() #gbls = marshal.loads(gbls)
defs = marshal.loads(defs)
clsr = marshal.loads(clsr)
fdct = marshal.loads(fdct)
func = FunctionType(code, gbls, name, defs, clsr)
func.fdct = fdct
return func(x)
def make_mappable(f, iterable):
if not isinstance(f, FunctionType): raise ValueError('argument must be a function')
name = f.__name__ # edited
code = marshal.dumps(f.__code__) # edited
defs = marshal.dumps(f.__defaults__) # edited
clsr = marshal.dumps(f.__closure__) # edited
fdct = marshal.dumps(f.__dict__) # edited
return _mappable, ((i,name,code,defs,clsr,fdct) for i in iterable)
After this function , the above problem code is also changed a little like this:
from multiprocessing import Pool
from poolable import make_applicable, make_mappable
def cube(x):
return x**3
if __name__ == "__main__":
pool = Pool(processes=2)
results = [pool.apply_async(*make_applicable(cube,x)) for x in range(1,7)]
print([result.get(timeout=10) for result in results])
And I got the output as :
[1, 8, 27, 64, 125, 216]
I am thinking that this post may be useful for some of the windows users.
If you need access to the internal states of a function, you're possibly better off using a class. You can make a class instance behave like a function by making it a callable, which is done by defining __call__
:
class StatefulFunction( object ):
def __init__( self ):
self.public_value = 'foo'
def __call__( self ):
return self.public_value
>> f = StatefulFunction()
>> f()
`foo`
>> f.public_value = 'bar'
>> f()
`bar`
I update my Hibernate JPA to 2.1 and It works.
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
In simple words View is the UI element which we interact with when we use an app,like button,edit text and image etc.View is the child class of Android.view.View While View group is the container which contains all these views inside it in addition to several othe viewgroups like linear or Frame Layout etc. Example if we design & take the root element as Linear layout now our main layout is linear layout inside it we can take another view group (i.e another Linear layout) & many other views like buttons or textview etc.
I ran across this problem with JBOSS EAP 6.1. I was able to deploy my code through eclipse to the JBOSS server but once I attempted to deploy the file as a WAR file to JBOSS I started getting this error.
The solution was configuring the web.xml to work properly with JBOSS by allowing the two to work together.
The following two lines were commented out in web.xml to allow JBOSS to do it's own configurations
<!--
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.your.package</param-value>
</init-param> -->
And then add the following context params after
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.resources</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.providers</param-name>
<param-value>false</param-value>
</context-param>
Note that with | char, you can get a warning with your IDE, for exemple I get warning with the last version of IntelliJ, So the best solution it's to use this syntax:
th:text="${'static_content - ' + you_variable}"
The fix is called "hard refresh" http://en.wikipedia.org/wiki/Wikipedia:Bypass_your_cache
In most Windows and Linux browsers: Hold down Ctrl and press F5.
In Apple Safari: Hold down ? Shift and click the Reload toolbar button.
In Chrome and Firefox for Mac: Hold down both ? Cmd+? Shift and press R.
Another alternative
for(String serverId : serverIds) {
sb.append(",");
sb.append(serverId);
}
sb.deleteCharAt(0);
The correct answer to this has already been given: no, you can't give the name of an enum, only it's value.
Nevertheless, just for fun, this will give you an enum and a lookup-table all in one and give you a means of printing it by name:
main.c:
#include "Enum.h"
CreateEnum(
EnumerationName,
ENUMValue1,
ENUMValue2,
ENUMValue3);
int main(void)
{
int i;
EnumerationName EnumInstance = ENUMValue1;
/* Prints "ENUMValue1" */
PrintEnumValue(EnumerationName, EnumInstance);
/* Prints:
* ENUMValue1
* ENUMValue2
* ENUMValue3
*/
for (i=0;i<3;i++)
{
PrintEnumValue(EnumerationName, i);
}
return 0;
}
Enum.h:
#include <stdio.h>
#include <string.h>
#ifdef NDEBUG
#define CreateEnum(name,...) \
typedef enum \
{ \
__VA_ARGS__ \
} name;
#define PrintEnumValue(name,value)
#else
#define CreateEnum(name,...) \
typedef enum \
{ \
__VA_ARGS__ \
} name; \
const char Lookup##name[] = \
#__VA_ARGS__;
#define PrintEnumValue(name, value) print_enum_value(Lookup##name, value)
void print_enum_value(const char *lookup, int value);
#endif
Enum.c
#include "Enum.h"
#ifndef NDEBUG
void print_enum_value(const char *lookup, int value)
{
char *lookup_copy;
int lookup_length;
char *pch;
lookup_length = strlen(lookup);
lookup_copy = malloc((1+lookup_length)*sizeof(char));
strcpy(lookup_copy, lookup);
pch = strtok(lookup_copy," ,");
while (pch != NULL)
{
if (value == 0)
{
printf("%s\n",pch);
break;
}
else
{
pch = strtok(NULL, " ,.-");
value--;
}
}
free(lookup_copy);
}
#endif
Disclaimer: don't do this.
replaceHtmlEntities(text) {
var tagsToReplace = {
'&': '&',
'<': '<',
'>': '>',
};
var newtext = text;
for (var tag in tagsToReplace) {
if (Reflect.apply({}.hasOwnProperty, this, [tagsToReplace, tag])) {
var regex = new RegExp(tag, 'g');
newtext = newtext.replace(regex, tagsToReplace[tag]);
}
}
return newtext;
}
You might want to start with an introduction to version control. This guide is specific to subversion, but the core concepts can be applied to most version control systems. After you have the basics, you can delve into the git guide.
You could do this manually or using IndexOf
method.
Manually:
int index = 43;
string piece = myString.Substring(index);
Using IndexOf you can see where the fullstop is:
int index = myString.IndexOf(".") + 1;
string piece = myString.Substring(index);
The stupid mistake I made to cause this error was to have the wrong package string in my AndroidManifest.xml
file. I'd left the string set in the tutorial, but had used my own when setting up the project.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="COM.YOU.YOURAPPNAME"
android:versionCode="1"
android:versionName="1.0" >
JpaRepository
The Spring Data JpaRepository
defines the following two methods:
getOne
, which returns an entity proxy that is suitable for setting a @ManyToOne
or @OneToOne
parent association when persisting a child entity.findById
, which returns the entity POJO after running the SELECT statement that loads the entity from the associated tableHowever, in your case, you didn't call either getOne
or findById
:
Person person = personRepository.findOne(1L);
So, I assume the findOne
method is a method you defined in the PersonRepository
. However, the findOne
method is not very useful in your case. Since you need to fetch the Person
along with is roles
collection, it's better to use a findOneWithRoles
method instead.
You can define a PersonRepositoryCustom
interface, as follows:
public interface PersonRepository
extends JpaRepository<Person, Long>, PersonRepositoryCustom {
}
public interface PersonRepositoryCustom {
Person findOneWithRoles(Long id);
}
And define its implementation like this:
public class PersonRepositoryImpl implements PersonRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
@Override
public Person findOneWithRoles(Long id)() {
return entityManager.createQuery("""
select p
from Person p
left join fetch p.roles
where p.id = :id
""", Person.class)
.setParameter("id", id)
.getSingleResult();
}
}
That's it!
__call__
allows to return arbitrary values, while __init__
being an constructor returns the instance of class implicitly. As other answers properly pointed out, __init__
is called just once, while it's possible to call __call__
multiple times, in case the initialized instance is assigned to intermediate variable.
>>> class Test:
... def __init__(self):
... return 'Hello'
...
>>> Test()
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __init__() should return None, not 'str'
>>> class Test2:
... def __call__(self):
... return 'Hello'
...
>>> Test2()()
'Hello'
>>>
>>> Test2()()
'Hello'
>>>
for i in iterator:
try:
# Do something.
pass
except:
# Continue to next iteration.
continue
Modern browsers (tested on Chrome, Firefox, Safari) implement some helper functions using the dollar sign $
that are very similar to jQuery (if the website doesn't define something using window.$
).
Those utilities are quite useful for selecting elements in the DOM and modifying them.
Wrap into an object
Something like this is a bit cleaner
const obj = {
X: 'dataX',
Y: 'dataY',
//...
}
const list = {
A: true && 'dataA',
B: false && 'dataB',
C: 'A' != 'B' && 'dataC',
D: 2000 < 100 && 'dataD',
// E: conditionE && 'dataE',
// F: conditionF && 'dataF',
//...
}
Object.keys(list).map(prop => list[prop] ? obj[prop] = list[prop] : null)
Wrap into an array
Or if you want to use Jamie Hill's method and have a very long list of conditions then you must write ...
syntax multiple times. To make it a bit cleaner, you can just wrap them into an array, then use reduce()
to return them as a single object.
const obj = {
X: 'dataX',
Y: 'dataY',
//...
...[
true && { A: 'dataA'},
false && { B: 'dataB'},
'A' != 'B' && { C: 'dataC'},
2000 < 100 && { D: 'dataD'},
// conditionE && { E: 'dataE'},
// conditionF && { F: 'dataF'},
//...
].reduce(( v1, v2 ) => ({ ...v1, ...v2 }))
}
Or using map()
function
const obj = {
X: 'dataX',
Y: 'dataY',
//...
}
const array = [
true && { A: 'dataA'},
false && { B: 'dataB'},
'A' != 'B' && { C: 'dataC'},
2000 < 100 && { D: 'dataD'},
// conditionE && { E: 'dataE'},
// conditionF && { F: 'dataF'},
//...
].map(val => Object.assign(obj, val))
I had the same problem and solved by doing following.
Go to Task Manager, click on services tab, order by pid's than if you find the related process, kill it otherwise, right click and click on show details, the process should be shown now. order by pid's than kill the related process.
First, get the LocationManager. Then, call LocationManager.getLastKnownPosition
. Then create a GeoCoder and call GeoCoder.getFromLocation
. Do this is in a separate thread!! This will give you a list of Address
objects. Call Address.getCountryName
and you got it.
Keep in mind that the last known position can be a bit stale, so if the user just crossed the border, you may not know about it for a while.
It happens when you are trying to access secure Website like Https.
I hope you missed 's'
Try Changing URL to curl -sS -u "username:password" https://www.example.com/backup.php
Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq
Save your JSON example to a file, say ex.json and then
yq -y '.' ex.json
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
I think you want something like this. The formatting is off, but it should give the essential information you want.
import java.util.Scanner;
public class BookstoreCredit
{
public static void computeDiscount(String name, double gpa)
{
double credits;
credits = gpa * 10;
System.out.println(name + " your GPA is " +
gpa + " so your credit is $" + credits);
}
public static void main (String args[])
{
String studentName;
double gradeAverage;
Scanner inputDevice = new Scanner(System.in);
System.out.println("Enter Student name: ");
studentName = inputDevice.nextLine();
System.out.println("Enter student GPA: ");
gradeAverage = inputDevice.nextDouble();
computeDiscount(studentName, gradeAverage);
}
}
You can pip install pickle by running command pip install pickle-mixin
.
Proceed to import it using import pickle
.
This can be then used normally.
OAuth v2 specs indicates:
Access token attributes and the methods used to access protected resources are beyond the scope of this specification and are defined by companion specifications.
My Authorisation Server has a webservice (SOAP) endpoint that allows the Resource Server to know whether the access_token is valid.
I would use .Equals()
for comparison instead of ==
.
Like so:
MyClass item = MyList.Find(item => item.name.Equals("foo"));
Particularly because it gives you options like StringComparison, which is awesome. Example:
MyClass item = MyList.Find(item => item.name.Equals("foo", StringComparison.InvariantCultureIgnoreCase);
This enables your code to ignore special characters, upper and lower case. There are more options.
The method jQuery (v1.10) uses to find this is:
var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
That is:
window.pageXOffset
first and uses that if it exists.document.documentElement.scrollLeft
.document.documentElement.clientLeft
if it exists.The subtraction of document.documentElement.clientLeft
/ Top
only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.
Convert String to Data
extension String {
func toData() -> Data {
return Data(self.utf8)
}
}
Convert Data to String
extension Data {
func toString() -> String {
return String(decoding: self, as: UTF8.self)
}
}
There are quite lots of answer based on situation.
1) Try to replace '$' with "jQuery"
2) Check that code you are executed are always below the main jquery script.
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
});
</script>
3) Pass $ into the function and add "jQuery" as a main function like below.
<script type="text/javascript">
jQuery(document).ready(function($){
});
</script>
In this example the file will be called myShell
First of all we will need to make this file we can just start off by typing the following:
sudo nano myShell
Notice we didn't put the .sh
extension?
That's because when we run it from the terminal we will only need to type myShell
in order to run our command!
Now, in nano the top line MUST be #!/bin/bash
then you may leave a new line before continuing.
For demonstration I will add a basic Hello World!
response
So, I type the following:
echo Hello World!
After that my example should look like this:
#!/bin/bash
echo Hello World!
Now save the file and then run this command:
chmod +x myShell
Now we have made the file executable we can move it to /usr/bin/
by using the following command:
sudo cp myShell /usr/bin/
Congrats! Our command is now done! In the terminal we can type myShell
and it should say Hello World!
I'm a little confused. "foo.html" is just the name of your template. There's no inherent relationship between the route name "foo" and the template name "foo.html".
To achieve the goal of not rewriting logic code for two different routes, I would just define a function and call that for both routes. I wouldn't use redirect because that actually redirects the client/browser which requires them to load two pages instead of one just to save you some coding time - which seems mean :-P
So maybe:
def super_cool_logic():
# execute common code here
@app.route("/foo")
def do_foo():
# do some logic here
super_cool_logic()
return render_template("foo.html")
@app.route("/baz")
def do_baz():
if some_condition:
return render_template("baz.html")
else:
super_cool_logic()
return render_template("foo.html", messages={"main":"Condition failed on page baz"})
I feel like I'm missing something though and there's a better way to achieve what you're trying to do (I'm not really sure what you're trying to do)
Using List.sort()
and Comparator.comparingLong()
numberList.sort(Comparator.comparingLong(x -> -x));
When I ended the process .Net Core Host
, everything built fine. I didn't have to close Visual Studio or do change anything else.
Here is full manifest code
<activity
android:name=".activities.MainActivity"
android:windowSoftInputMode="adjustResize"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
I had this issue for 2 days, let me show you how I fixed it.
This was how the code looked when I was getting the error:
request.onload = function() {
// This is where we begin accessing the Json
let data = JSON.parse(this.response);
console.log(data)
}
This is what I changed to get the result I wanted:
request.onload = function() {
// This is where we begin accessing the Json
let data = JSON.parse(this.responseText);
console.log(data)
}
So all I really did was change
this.response
to this.responseText
.
You can write like this:
CSS
span{
background: none repeat scroll 0 0 #F8F8F8;
border: 5px solid #DFDFDF;
color: #717171;
font-size: 13px;
height: 30px;
letter-spacing: 1px;
line-height: 30px;
margin: 0 auto;
position: relative;
text-align: center;
text-transform: uppercase;
top: -80px;
left:-30px;
display:none;
padding:0 20px;
}
span:after{
content:'';
position:absolute;
bottom:-10px;
width:10px;
height:10px;
border-bottom:5px solid #dfdfdf;
border-right:5px solid #dfdfdf;
background:#f8f8f8;
left:50%;
margin-left:-5px;
-moz-transform:rotate(45deg);
-webkit-transform:rotate(45deg);
transform:rotate(45deg);
}
p{
margin:100px;
float:left;
position:relative;
cursor:pointer;
}
p:hover span{
display:block;
}
HTML
<p>Hover here<span>some text here ?</span></p>
Check this http://jsfiddle.net/UNs9J/1/
You can simulate a readonly select box using the CSS pointer-events property:
select[readonly]
{
pointer-events: none;
}
The HTML tabindex property will also prevent it from being selected by keyboard tabbing:
<select tabindex="-1">
select[readonly]_x000D_
{_x000D_
pointer-events: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* irrelevent styling */_x000D_
_x000D_
*_x000D_
{_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
*[readonly]_x000D_
{_x000D_
background: #fafafa;_x000D_
border: 1px solid #ccc;_x000D_
color: #555;_x000D_
}_x000D_
_x000D_
input, select_x000D_
{_x000D_
display:block;_x000D_
width: 20rem;_x000D_
padding: 0.5rem;_x000D_
margin-bottom: 1rem;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="this is a normal text box">_x000D_
<input type="text" readonly value="this is a readonly text box">_x000D_
<select readonly tabindex="-1">_x000D_
<option>This is a readonly select box</option>_x000D_
<option>Option 2</option>_x000D_
</select>_x000D_
<select>_x000D_
<option>This is a normal select box</option>_x000D_
<option>Option 2</option>_x000D_
</select>_x000D_
</form>
_x000D_
Install git and tortoise git for windows and make sure it is on your path, (the installer for Tortoise Git includes options for the command line tools and ensuring that it is on the path - select them).
You will need to close and re-open any existing command line sessions for the changes to take effect.
Then you should be able to run npm install
successfully or move on to the next problem!
For Java < 7 you can use if-else along with Exception:
try {
// common logic to handle both exceptions
} catch (Exception ex) {
if (ex instanceof Exception1 || ex instanceof Exception2) {
}
else {
throw ex;
// or if you don't want to have to declare Exception use
// throw new RuntimeException(ex);
}
}
Edited and replaced Throwable with Exception.
You can iterate DefaultView
as the following code by Indexer
:
DataTable dt = new DataTable();
// add some rows to your table
// ...
dt.DefaultView.Sort = "OneColumnName ASC"; // For example
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow oRow = dt.DefaultView[i].Row;
// Do your stuff with oRow
// ...
}
Use this to convert String to Blob. Where connection is the connection to db object.
String strContent = s;
byte[] byteConent = strContent.getBytes();
Blob blob = connection.createBlob();//Where connection is the connection to db object.
blob.setBytes(1, byteContent);
This full example includes passing data back to the Activity.
A layout with an EditText
is used for this simple example, but you can replace it with anything you like.
custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
The key parts are
setView
to assign the custom layout to the AlertDialog.Builder
This is the full code from the example project shown in the image above:
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showAlertDialogButtonClicked(View view) {
// create an alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Name");
// set the custom layout
final View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null);
builder.setView(customLayout);
// add a button
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// send data from the AlertDialog to the Activity
EditText editText = customLayout.findViewById(R.id.editText);
sendDialogDataToActivity(editText.getText().toString());
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
}
// do something with the data coming from the AlertDialog
private void sendDialogDataToActivity(String data) {
Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
}
}
DialogFragment
subclass as is described in the documentation.For those looking for a dynamic solution to embed Matplotlib in PyQt5 (even plot data using drag and drop). In PyQt5 you need to use super on the main window class to accept the drops. The dropevent function can be used to get the filename and rest is simple:
def dropEvent(self,e):
"""
This function will enable the drop file directly on to the
main window. The file location will be stored in the self.filename
"""
if e.mimeData().hasUrls:
e.setDropAction(QtCore.Qt.CopyAction)
e.accept()
for url in e.mimeData().urls():
if op_sys == 'Darwin':
fname = str(NSURL.URLWithString_(str(url.toString())).filePathURL().path())
else:
fname = str(url.toLocalFile())
self.filename = fname
print("GOT ADDRESS:",self.filename)
self.readData()
else:
e.ignore() # just like above functions
For starters the reference complete code gives this output:
Here is a C# implementation of the *nix cksum command line utility for windows https://cksum.codeplex.com/
The answer is no.
I would like to draw your attention towards this book Pro Android 2 that states:
It is also worth noting a few constraints regarding resources. First, Android supports only a linear list of files within the predefined folders under res. For example, it does not support nested folders under the layout folder (or the other folders under res).
Second, there are some similarities between the assets folder and the raw folder under res. Both folders can contain raw files, but the files within raw are considered resources and the files within assets are not.
Note that because the contents of the assets folder are not considered resources, you can put an arbitrary hierarchy of folders and files within it.
I am answering this old question just because it still shows up in google queries and I think one optimal answer is missing. Try this code: use ::before or ::after
Updating setuptools has worked out fine for me.
sudo pip install --upgrade setuptools
The absolute best analog of tic and toc would be to simply define them in python.
def tic():
#Homemade version of matlab tic and toc functions
import time
global startTime_for_tictoc
startTime_for_tictoc = time.time()
def toc():
import time
if 'startTime_for_tictoc' in globals():
print "Elapsed time is " + str(time.time() - startTime_for_tictoc) + " seconds."
else:
print "Toc: start time not set"
Then you can use them as:
tic()
# do stuff
toc()
If you are writing a web app or single page application (SPA) where routing takes place in the app/browser rather than a round-trip to the server, you can do the following:
window.history.pushState({ prevUrl: window.location.href }, null, "/new/path/in/your/app")
Then, in your new route, you can do the following to retrieve the previous URL:
window.history.state.prevUrl // your previous url
I ended up setting my own drop shadow for the toolbar, thought it might helpful for anyone looking for it:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:orientation="vertical">
<android.support.v7.widget.Toolbar android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/color_alizarin"
android:titleTextAppearance="@color/White"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- **** Place Your Content Here **** -->
<View android:layout_width="match_parent"
android:layout_height="5dp"
android:background="@drawable/toolbar_dropshadow"/>
</FrameLayout>
</LinearLayout>
@drawable/toolbar_dropshadow:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="@android:color/transparent"
android:endColor="#88333333"
android:angle="90"/>
</shape>
@color/color_alizarin
<color name="color_alizarin">#e74c3c</color>
?? EASY: All you need is a forced push. Because you might have created
readme.md
file on Github and you haven't pulled it yet.
git push -f origin master
And here's a GIF.
?? BEWARE: Using force
can change the history for other folks on the same project. Basically, if you don't care about a file being deleted for everyone, just go ahead. Especially if you're the only dev on the project.
After getting the help from @Blender, @ekhumoro and @Dan, I understand the Linux and Python more than before. Thank you. I got the an idea by @ekhumoro, it is I didn't install PyQt5 correctly. So I delete PyQt5 folder and download again. And redo everything from very start.
After redoing, I got the error as my last update at my question. So, when I search at stack, I got the following solution from here
sudo ln -s /usr/include/python2.7 /usr/local/include/python2.7
And then, I did "sudo make" and "sudo make install" step by step. After "sudo make install", I got the following error. But I ignored it and I created a simple design with qt designer. And I converted it into python file by pyuic5. Everything are going well.
install -m 755 -p /home/thura/PyQt/pyuic5 /usr/bin/
strip /usr/bin/pyuic5
strip:/usr/bin/pyuic5: File format not recognized
make: [install_pyuic5] Error 1 (ignored)
You could use a navigation property if its available. It produces an inner join in the SQL.
from s in db.Services
where s.ServiceAssignment.LocationId == 1
select s
Assuming that your original dataset is similar to the one you created (i.e. with NA
as character
. You could specify na.strings
while reading the data using read.table
. But, I guess NAs would be detected automatically.
The price
column is factor
which needs to be converted to numeric
class. When you use as.numeric
, all the non-numeric elements (i.e. "NA"
, FALSE) gets coerced to NA
) with a warning.
library(dplyr)
df %>%
mutate(price=as.numeric(as.character(price))) %>%
group_by(company, year, product) %>%
summarise(total.count=n(),
count=sum(is.na(price)),
avg.price=mean(price,na.rm=TRUE),
max.price=max(price, na.rm=TRUE))
I am using the same dataset
(except the ...
row) that was showed.
df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
"Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
"7.12", "12.99", "10.99", "NA",FALSE)))
Once upon a time I was looking for something similar - a lightweight yet fully functional HTTP server that I could easily embed and customize. I found two types of potential solutions:
So... I set out to write JLHTTP - The Java Lightweight HTTP Server.
You can embed it in any project as a single (if rather long) source file, or as a ~50K jar (~35K stripped) with no dependencies. It strives to be RFC-compliant and includes extensive documentation and many useful features while keeping bloat to a minimum.
Features include: virtual hosts, file serving from disk, mime type mappings via standard mime.types file, directory index generation, welcome files, support for all HTTP methods, conditional ETags and If-* header support, chunked transfer encoding, gzip/deflate compression, basic HTTPS (as provided by the JVM), partial content (download continuation), multipart/form-data handling for file uploads, multiple context handlers via API or annotations, parameter parsing (query string or x-www-form-urlencoded body), etc.
I hope others find it useful :-)
Please try this. Maybe this could help you. It works for me.
string sValue = (range.Cells[_row, _column] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
//_row,_column your column & row number
//eg: string sValue = (sheet.Cells[i + 9, 12] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
//sValue has your value
Try using:
console.log($("#"+d));
This will remove the extra quotes you were using.
There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating
event.
The Validating
event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true
the TextBox doesn't lose the focus.
MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order
Enter
GotFocus
Leave
Validating
Validated
LostFocus
When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:
Enter
GotFocus
LostFocus
Leave
Validating
Validated
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text != "something")
e.Cancel = true;
}
You can use the ErrorProvider
to visualize that your TextBox is not valid.
Check out Using Error Provider Control in Windows Forms and C#
This problem can occur if a class tries to get value of a non-existent key in web.config
.
For example, the class has a static variable ClientID
private static string ClientID = System.Configuration.ConfigurationSettings.AppSettings["GoogleCalendarApplicationClientID"].ToString();
but the web.config
doesn't contain the 'GoogleCalendarApplicationClientID' key, then the error will be thrown on any static function call or any class instance creation
We can maintain dynamic height for collection view cell without xib(only using storyboard).
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
NSAttributedString* labelString = [[NSAttributedString alloc] initWithString:@"Your long string goes here" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0]}];
CGRect cellRect = [labelString boundingRectWithSize:CGSizeMake(cellWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
return CGSizeMake(cellWidth, cellRect.size.height);
}
Make sure that numberOfLines in IB should be 0.
Open tmux configuration file with the following command:
vim ~/.tmux.conf
In the configuration file add the following line:
set -g history-limit 5000
Log out and log in again, start a new tmux windows and your limit is 5000 now.
str="1w 2d 1h"
regex="([0-9])w ([0-9])d ([0-9])h"
if [[ $str =~ $regex ]]
then
week="${BASH_REMATCH[1]}"
day="${BASH_REMATCH[2]}"
hour="${BASH_REMATCH[3]}"
echo $week --- $day ---- $hour
fi
output: 1 --- 2 ---- 1
Try this:
SELECT Count(Student_ID) as 'StudentCount'
FROM CourseSemOne
where Student_ID=3
Having Count(Student_ID) < 6 and Count(Student_ID) > 0;
With React16.x, if you want to invoke a callback function on state change using useState
hook, you can use the useEffect
hook attached to the state change.
import React, { useEffect } from 'react';
useEffect(() => {
props.getChildChange(name); // using camelCase for variable name is recommended.
}, [name]); // this will call getChildChange when ever name changes.
You could also use
ImageIcon background = new ImageIcon("Background/background.png");
JLabel label = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(background);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(label);
if your working with a absolut value as layout.
Create Table as select (CTAS) is possible in Hive.
You can try out below command:
CREATE TABLE new_test
row format delimited
fields terminated by '|'
STORED AS RCFile
AS select * from source where col=1
Create table like is also possible in Hive.
If you reconfigure IIS7 to use your new location, then there's no problem. Just test that the new location is working, before deleting the old location.
Change IIS7 Inetpub path
- Open %windir%\system32\inetsrv\config\applicationhost.config and search for
%SystemDrive%\inetpub\wwwroot
- Change the path.
var http = require('http');
var url = process.argv[2];
http.get(url, function(response) {
var finalData = "";
response.on("data", function (data) {
finalData += data.toString();
});
response.on("end", function() {
console.log(finalData.length);
console.log(finalData.toString());
});
});
Set "VM options" like: "-cp $Classpath$;your_classpath"
I had the same problem. in Intellj, when i want to use h2 database when my program was running i got the same error. For solve this problem i changed the connection url from
spring.datasource.url=jdbc:h2:file:~/ipinbarbot
to:
spring.datasource.url=jdbc:h2:~/ipinbarbot;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE
And then my problem gone away. now i can connect to "ipinbarbot" database when my program is. If you use Hibernate, also don't forget to have:
spring.jpa.hibernate.ddl-auto = update
goodluck
All aforementioned suggestions use %s
placeholder for subject. I'll recommend to use %B
because %s
formatting preserves new lines and multiple lines commit message appears squashed.
git log --pretty=format:"%h%x09%an%x09%ai%x09%B"
lookup = 'the dog barked'
with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if lookup in line:
print 'found at line:', num
Following worked for me
curl -O -L https://sourceforge.net/projects/sshpass/files/sshpass/1.06/sshpass-1.06.tar.gz && tar xvzf sshpass-1.06.tar.gz
cd sshpass-1.06/
./configure
sudo make install
You need to change 3 things in your code:
var privateField = "hello"
with this.privateField = "hello"
.privateField
with this.privateField
.privateField
with this.privateField
.The final code would be the following:
TestClass = function(){
this.privateField = "hello";
this.nonProtoHello = function(){alert(this.privateField)};
}
TestClass.prototype.prototypeHello = function(){alert(this.privateField)};
var t = new TestClass();
t.prototypeHello()
Have you installed the Apple developer tools? What happens if you type gcc -v ?
It look as if you do not have downloaded the development stuff. You can get it for free (after registration) from http://developer.apple.com/
It's not so difficult.
You can inspect the available functions of the loaded object, and if you find the one you're looking for by name, then snoop its expected parms, if any. If it's the call you're trying to find, then call it using the MethodInfo object's Invoke method.
Another option is to simply build your external objects to an interface, and cast the loaded object to that interface. If successful, call the function natively.
This is pretty simple stuff.
JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>();
foreach (JToken attribute in attributes)
{
JProperty jProperty = attribute.ToObject<JProperty>();
string propertyName = jProperty.Name;
}
window_handles
should give you the references to all open windows.
this is what the docu has to say about switching windows.
I needed to use a link with onLoad attribute in my head where div is not allowed so this caused me significant pain. My current workaround is to close the original script tag, do what I need to do, then open script tag (to be closed by the original). Hope this might help someone who has absolutely no other choice:
<script dangerouslySetInnerHTML={{ __html: `</script>
<link rel="preload" href="https://fonts.googleapis.com/css?family=Open+Sans" as="style" onLoad="this.onload=null;this.rel='stylesheet'" crossOrigin="anonymous"/>
<script>`,}}/>
In addition to what Nick has said you can find out more at Streamed Lines: Branching Patterns for Parallel Software Development
In this figure main
is the trunk, rel1-maint
is a branch and 1.0
is a tag.
You should be using @RequestParam
instead of @ModelAttribute
, e.g.
@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id,
@RequestParam String someAttr) {
}
You can even omit @RequestParam
altogether if you choose, and Spring will assume that's what it is:
@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id,
String someAttr) {
}
Use to_datetime
, there is no need for a format string the parser is man/woman enough to handle it:
In [51]:
pd.to_datetime(df['I_DATE'])
Out[51]:
0 2012-03-28 14:15:00
1 2012-03-28 14:17:28
2 2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]
To access the date/day/time component use the dt
accessor:
In [54]:
df['I_DATE'].dt.date
Out[54]:
0 2012-03-28
1 2012-03-28
2 2012-03-28
dtype: object
In [56]:
df['I_DATE'].dt.time
Out[56]:
0 14:15:00
1 14:17:28
2 14:50:50
dtype: object
You can use strings to filter as an example:
In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]
Out[59]:
date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09
@jing: "The DirectoryInfo solution is much faster then this (especially for network path)"
I cant confirm this. It seems as if Directory.GetFiles triggers a filesystem or network cache. The first request takes a while, but the following requests are much faster, even if new files were added. In my test I did a Directory.getfiles and a info.GetFiles with the same patterns and both run equally
GetFiles done 437834 in00:00:20.4812480
process files done 437834 in00:00:00.9300573
GetFiles by Dirinfo(2) done 437834 in00:00:20.7412646
Without the main sentinel, the code would be executed even if the script were imported as a module.
Hopefully this can save someone a headache. I got this error after upgrading my react-native version. Confusingly it only appeared on the android side of things.
My file structure includes an index.ios.js
and an index.android.js
. Both contain the code:
AppRegistry.registerComponent('App', () => App);
What I had to do was, in android/app/src/main/java/com/{projectName}/MainApplication.java
, change index
to index.android
:
@Override
protected String getJSMainModuleName() {
return "index.android"; // was "index"
}
Then in app/build/build.gradle
, change the entryFile
from index.js
to index.android.js
project.ext.react = [
entryFile: "index.android.js" // was index.js"
]
All third=party tools mentioned below are 100% free.
I’ve used ApexSQL Search with good success for searching both objects and data in tables. It comes with several other features such as relationship diagrams and such…
I was a bit slow on large (40GB TFS Database) databases though…
Apart from this there is also SSMS Tools pack that offers a lot of other features that are quite useful even though these are not directly related to searching text.
What you want is impossible.
A Date
object represents an "absolute" moment in time. You cannot "remove the time part" from it. When you print a Date
object directly with System.out.println(date)
, it will always be formatted in a default format that includes the time. There is nothing you can do to change that.
Instead of somehow trying to use class Date
for something that it was not designed for, you should look for another solution. For example, use SimpleDateFormat
to format the date in whatever format you want.
The Java date and calendar APIs are unfortunately not the most well-designed classes of the standard Java API. There's a library called Joda-Time which has a much better and more powerful API.
Joda-Time has a number of special classes to support dates, times, periods, durations, etc. If you want to work with just a date without a time, then Joda-Time's LocalDate
class would be what you'd use.
I started working on this problem a long time ago, trying to write my own binary to decimal converter function. I don't actually know how to convert decimal to binary though! I just revisited it today and figured it out and this is what I came up with. I'm not sure if this is what you need, but here it is:
def __degree(number):
power = 1
while number % (10**power) != number:
power += 1
return power
def __getDigits(number):
digits = []
degree = __degree(number)
for x in range(0, degree):
digits.append(int(((number % (10**(degree-x))) - (number % (10**(degree-x-1)))) / (10**(degree-x-1))))
return digits
def binaryToDecimal(number):
list = __getDigits(number)
decimalValue = 0
for x in range(0, len(list)):
if (list[x] is 1):
decimalValue += 2**(len(list) - x - 1)
return decimalValue
Again, I'm still learning Python just on my own, hopefully this helps. The first function determines how many digits there are, the second function actually figures out they are and returns them in a list, and the third function is the only one you actually need to call, and it calculates the decimal value. If your teacher actually wanted you to write your own converter, this works, I haven't tested it with every number, but it seems to work perfectly! I'm sure you'll all find the bugs for me! So anyway, I just called it like:
binaryNum = int(input("Enter a binary number: "))
print(binaryToDecimal(binaryNum))
This prints out the correct result. Cheers!
Use:
SELECT *
FROM `table`
WHERE INSTR(`column`, '{$needle}') > 0
Reference:
This will not work:
wget -q -S -O - google.com 1>wget.txt 2>&1
since redirects are evaluated right to left, this sends html to wget.txt and the header to STDOUT:
wget -q -S -O - google.com 2>&1 1>wget.txt
Agree with all above answers of using MutableList but you can also add/remove from List and get a new list as below.
val newListWithElement = existingList + listOf(element)
val newListMinusElement = existingList - listOf(element)
Or
val newListWithElement = existingList.plus(element)
val newListMinusElement = existingList.minus(element)
I think this way also a normal way. But sorry, I can't describe in English ((
submitHandler = e => {_x000D_
e.preventDefault()_x000D_
console.log(this.state)_x000D_
fetch('http://localhost:5000/questions',{_x000D_
method: 'POST',_x000D_
headers: {_x000D_
Accept: 'application/json',_x000D_
'Content-Type': 'application/json',_x000D_
},_x000D_
body: JSON.stringify(this.state)_x000D_
}).then(response => {_x000D_
console.log(response)_x000D_
})_x000D_
.catch(error =>{_x000D_
console.log(error)_x000D_
})_x000D_
_x000D_
}
_x000D_
https://googlechrome.github.io/samples/fetch-api/fetch-post.html
fetch('url/questions',{ method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(this.state) }).then(response => { console.log(response) }) .catch(error =>{ console.log(error) })
Just making any of the parameters for division in floating-point format also produces the output in floating-point.
Example:
>>> 4.0/3
1.3333333333333333
or,
>>> 4 / 3.0
1.3333333333333333
or,
>>> 4 / float(3)
1.3333333333333333
or,
>>> float(4) / 3
1.3333333333333333
Just found a quick and simple solution to discover type of a variable.
ES6
export const isType = (type, val) => val.constructor.name.toLowerCase() === type.toLowerCase();
ES5
function isType(type, val) {
return val.constructor.name.toLowerCase() === type.toLowerCase();
}
Examples:
isType('array', [])
true
isType('array', {})
false
isType('string', '')
true
isType('string', 1)
false
isType('number', '')
false
isType('number', 1)
true
isType('boolean', 1)
false
isType('boolean', true)
true
EDIT
Improvment to prevent 'undefined' and 'null' values:
ES6
export const isType = (type, val) => !!(val.constructor && val.constructor.name.toLowerCase() === type.toLowerCase());
ES5
function isType(type, val) {
return !!(val.constructor && val.constructor.name.toLowerCase() === type.toLowerCase());
}
Another nice and efficient approach - is to pass rows for insertion as 1 argument, which is array of json objects.
E.g. you passing argument:
[ {id: 18, score: 1}, { id: 19, score: 5} ]
It is array, which may contain any amount of objects inside. Then your SQL looks like:
INSERT INTO links (parent_id, child_id, score)
SELECT 123, (r->>'id')::int, (r->>'score')::int
FROM unnest($1::json[]) as r
Notice: Your postgress must be new enough, to support json
Package data.table
includes last
function
library(data.table)
last(c(1:10))
# [1] 10
An additional dictionary example that is useful for containing frequency of occurence.
Outside of loop:
Dim dict As New Scripting.dictionary
Dim MyVar as String
Within a loop:
'dictionary
If dict.Exists(MyVar) Then
dict.Item(MyVar) = dict.Item(MyVar) + 1 'increment
Else
dict.Item(MyVar) = 1 'set as 1st occurence
End If
To check on frequency:
Dim i As Integer
For i = 0 To dict.Count - 1 ' lower index 0 (instead of 1)
Debug.Print dict.Items(i) & " " & dict.Keys(i)
Next i
From documentation:
To comply with the
SQL
standard,IN
returnsNULL
not only if the expression on the left hand side isNULL
, but also if no match is found in the list and one of the expressions in the list isNULL
.
This is exactly your case.
Both IN
and NOT IN
return NULL
which is not an acceptable condition for WHERE
clause.
Rewrite your query as follows:
SELECT *
FROM match m
WHERE NOT EXISTS
(
SELECT 1
FROM email e
WHERE e.id = m.id
)
To read the files from src/resources folder then try this :
DataSource fds = new FileDataSource(getFileHandle("images/sample.jpeg"));
public static File getFileHandle(String fileName){
return new File(YourClassName.class.getClassLoader().getResource(fileName).getFile());
}
in case of non static reference:
return new File(getClass().getClassLoader().getResource(fileName).getFile());
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-select-box It's working well in my case
$(document).ready(function(){_x000D_
$("select").change(function(){_x000D_
$(this).find("option:selected").each(function(){_x000D_
var optionValue = $(this).attr("value");_x000D_
if(optionValue){_x000D_
$(".box").not("." + optionValue).hide();_x000D_
$("." + optionValue).show();_x000D_
} else{_x000D_
$(".box").hide();_x000D_
}_x000D_
});_x000D_
}).change();_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>jQuery Show Hide Elements Using Select Box</title>_x000D_
<style>_x000D_
.box{_x000D_
color: #fff;_x000D_
padding: 50px;_x000D_
display: none;_x000D_
margin-top: 10px;_x000D_
}_x000D_
.red{ background: #ff0000; }_x000D_
.green{ background: #228B22; }_x000D_
.blue{ background: #0000ff; }_x000D_
</style>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
<select>_x000D_
<option>Choose Color</option>_x000D_
<option value="red">Red</option>_x000D_
<option value="green">Green</option>_x000D_
<option value="blue">Blue</option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="red box">You have selected <strong>red option</strong> so i am here</div>_x000D_
<div class="green box">You have selected <strong>green option</strong> so i am here</div>_x000D_
<div class="blue box">You have selected <strong>blue option</strong> so i am here</div>_x000D_
</body>_x000D_
</html>
_x000D_
I'll disagree with The Tin Man here. I regard rbenv as preferable to RVM. rbenv
doesn't interfere drastically with your shell the way RVM does, and it lets you add separate Ruby installations in ordinary folders that you can examine directly. It allows you to compile Ruby yourself. Good outline of the differences here: https://github.com/sstephenson/rbenv/wiki/Why-rbenv%3F
I provide instructions for compiling Ruby 1.9 for rbenv here. Further, more detailed information here. I have used this technique with easy success on Snow Leopard, Lion, and Mountain Lion.
Check http://msdn.microsoft.com/en-us/library/dd203099.aspx
under Cryptography Application Block.
Don't know if you will get your answer, but it's worth a try.
Edit after Comment.
Ok then check this code.
using System.Security.Cryptography;
public static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) {
X509Certificate2 myCertificate;
try{
myCertificate = new X509Certificate2(PathToPrivateKeyFile);
} catch{
throw new CryptographicException("Unable to open key file.");
}
RSACryptoServiceProvider rsaObj;
if(myCertificate.HasPrivateKey) {
rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey;
} else
throw new CryptographicException("Private key not contained within certificate.");
if(rsaObj == null)
return String.Empty;
byte[] decryptedBytes;
try{
decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false);
} catch {
throw new CryptographicException("Unable to decrypt data.");
}
// Check to make sure we decrpyted the string
if(decryptedBytes.Length == 0)
return String.Empty;
else
return System.Text.Encoding.UTF8.GetString(decryptedBytes);
}
In javascript, navigation type 2 means browser's back or forward button clicked and the browser is actually taking content from cache.
if(performance.navigation.type == 2) {
//Do your code here
}
Because it makes these things so easy, you could consider using a JavaScript library like jQuery to do this:
<script>
$(document).ready(function() {
$('img.thumbnail').click(function() {
window.location.href = this.id + '.html';
});
});
</script>
Basically, it attaches an onClick
event to all images with class thumbnail
to redirect to the corresponding HTML page (id
+ .html
). Then you only need the images in your HTML (without the a
elements), like this:
<img src="bottle.jpg" alt="bottle" class="thumbnail" id="bottle" />
<img src="glass.jpg" alt="glass" class="thumbnail" id="glass" />
It 'happened to me! The problem is that somehow you include a file with the same file name of the class thus invalidating the same class!
Check the path of inclusion and these checks files with the same name!
I had to do something similar, trying to convert a string of numbers into a timespan by adding in :
and .
. Basically I was taking 235959999 and needing to convert it to 23:59:59.999. For me it was easy because I knew where I needed to "insert" said characters.
ts = ts.Insert(6,".");
ts = ts.Insert(4,":");
ts = ts.Insert(2,":");
Basically reassigning ts to itself with the inserted character. I worked my way from the back to front, because I was lazy and didn't want to do additional math for the other inserted characters.
You could try something similar by doing:
alpha = alpha.Insert(5,"-");
alpha = alpha.Insert(11,"-"); //add 1 to account for 1 -
alpha = alpha.Insert(17,"-"); //add 2 to account for 2 -
...
Depends on the hosting os. Sites that are hosted on Windows tend to be case insensitive as the underlying file system is case insensitive. Sites hosted on Unix type systems tend to be case sensitive as their underlying file systems are typically case sensitive. The host name part of the URL is always case insensitive, it's the rest of the path that varies.
you need nested foreach loops
foreach($samplearr as $key => $item){
echo $key;
foreach($item as $detail){
echo $detail['value1'] . " " . $detail['value2']
}
}
This my variant of the solution based on LINQ and the Descendants method of the XDocument
class
using System;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
XDocument xml = XDocument.Parse(@"
<root>
<child id='1'/>
<child id='2'>
<subChild id='3'>
<extChild id='5' />
<extChild id='6' />
</subChild>
<subChild id='4'>
<extChild id='7' />
</subChild>
</child>
</root>");
xml.Descendants().Where(p => p.Name.LocalName == "extChild")
.ToList()
.ForEach(e => Console.WriteLine(e));
Console.ReadLine();
}
}
While it's true that json
is a built-in module, I also found that on an Ubuntu system with python-minimal
installed, you DO have python
but you can't do import json
. And then I understand that you would try to install the module using pip!
If you have python-minimal
you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json
module. The solution is to install an additional package, called libpython2.7-stdlib
, to install all 'default' python libraries.
sudo apt install libpython2.7-stdlib
And then you can do import json
in python and it would work!
I had this similar issue. I wanted to set a class after looking at multiple expressions. ngClass can evaluate a method inside the component code and tell you what to do.
So inside an *ngFor:
<div [ngClass]="{'shrink': shouldShrink(a.category1, a.category2), 'showAll': section == 'allwork' }">{{a.listing}}</div>
And inside the component:
section = 'allwork';
shouldShrink(cat1, cat2) {
return this.section === cat1 || this.section === cat2 ? false : true;
}
Here I need to calculate if i should shrink a div based on if a 2 different categories have matched what the selected category is. And it works. So from there you can computer a true/false for the [ngClass] based on what your method returns given the inputs.
Sometimes this has to do with configuration changes. When we upgraded from Tomncat 6.0.14 to 6.0.26, we had seen something similar. here is the solution http://www.skill-guru.com/blog/2010/08/22/tomcat-6-0-26-shutdown-reports-a-web-application-created-a-threadlocal-threadlocal-has-been-forcibly-removed/
SELECT UNIQUE
is old syntax supported by Oracle's flavor of SQL. It is synonymous with SELECT DISTINCT
.
Use SELECT DISTINCT
because this is standard SQL, and SELECT UNIQUE
is non-standard, and in database brands other than Oracle, SELECT UNIQUE
may not be recognized at all.
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
select_statement
Example :
CREATE TEMPORARY TABLE IF NOT EXISTS mytable
(id int(11) NOT NULL, PRIMARY KEY (id)) ENGINE=MyISAM;
INSERT IGNORE INTO mytable SELECT id FROM table WHERE xyz;
php's email()
function hands the email over to a underlying mail transfer agent
which is usually postfix
on linux systems
so the preferred method on linux is to configure your postfix to use a relayhost, which is done by a line of
relayhost = smtp.example.com
in /etc/postfix/main.cf
however in the OP's scenario I somehow suspect that it's a job that his hosting team
should have done
For Sequelize 4
Query
SELECT * FROM Student WHERE LastName='Doe'
AND (FirstName = "John" or FirstName = "Jane") AND Age BETWEEN 18 AND 24
Syntax with Operators
const Op = require('Sequelize').Op;
var r = await to (Student.findAll(
{
where: {
LastName: "Doe",
FirstName: {
[Op.or]: ["John", "Jane"]
},
Age: {
// [Op.gt]: 18
[Op.between]: [18, 24]
}
}
}
));
Notes
$
(e.g $and
, $or
...){freezeTableName: true}
set in the table model then Sequelize will query against the plural form of its name ( Student -> Students )I'd probably go with this (I know its not pure linq), keep a reference to the original list if you want to retain all items, and you should find the updated values are in there:
foreach (var mc in list.Where(x => x.Name == "height"))
mc.Value = 30;
A perhaps cheesy way to clear the screen, but one that will work on any platform I know of, is as follows:
for i in xrange(0,100):
print ""
It is valid. You can, for example, use it to show modals (or similar things that respond to data-toggle
and data-target
attributes).
Something like:
<a role="button" data-toggle="modal" data-target=".bs-example-modal-sm" aria-hidden="true"><i class="fa fa-phone"></i></a>
Here I use the font-awesome icon, which is better as a a
tag rather than a button
, to show a modal. Also, setting role="button"
makes the pointer change to an action type. Without either href
or role="button"
, the cursor pointer does not change.
You can use Scanner class
Import first :
import java.util.Scanner;
Then you use like this.
Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();
Side note : If you are using nextInt()
with nextLine()
you probably could have some trouble cause nextInt()
does not read the last newline character of input and so nextLine()
then is not gonna to be executed with desired behaviour. Read more in how to solve it in this previous question Skipping nextLine using nextInt.
we can directly see the indexes on to the table if we know the index name with below :
select * from all_indexes where index_name= 'your index'
If you want to rename multiple files in a single command - let's say you want to convert all *.txt
files - here is the command:
find . -name "*.txt" -exec iconv -f WINDOWS-1252 -t UTF-8 {} -o {}.ren \; -a -exec mv {}.ren {} \;
Don't forget the option "-o", which lets you download anywhere you want, although you have to create "archives", "lock" and "partial" first (the command prints what's needed).
apt-get install -d -o=dir::cache=/tmp whateveryouwant
How can I declare a class type, so that I ensure the object is a constructor of a general class?
A Constructor type could be defined as:
type AConstructorTypeOf<T> = new (...args:any[]) => T;
class A { ... }
function factory(Ctor: AConstructorTypeOf<A>){
return new Ctor();
}
const aInstance = factory(A);
Try this code its working Firefox, Chrome, IE
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value="" selected>---Select---</option>
<option value="https://www.google.com">Google</option>
<option value="https://www.google.com">Google</option>
<option value="https://www.google.com">Google</option>
<option value="https://www.google.com">Google</option>