This kind of error usually means that some parts of (JS) code were not loaded. That the state which is inside of ui-sref
is missing.
There is a working example
I am not an expert in ionic, so this example should show that it would be working, but I used some more tricks (parent for tabs)
This is a bit adjusted state def:
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("/index.html");
$stateProvider
.state('app', {
abstract: true,
templateUrl: "tpl.menu.html",
})
$stateProvider.state('index', {
url: '/',
templateUrl: "tpl.index.html",
parent: "app",
});
$stateProvider.state('register', {
url: "/register",
templateUrl: "tpl.register.html",
parent: "app",
});
$urlRouterProvider.otherwise('/');
})
And here we have the parent view with tabs, and their content:
<ion-tabs class="tabs-icon-top">
<ion-tab title="Index" icon="icon ion-home" ui-sref="index">
<ion-nav-view name=""></ion-nav-view>
</ion-tab>
<ion-tab title="Register" icon="icon ion-person" ui-sref="register">
<ion-nav-view name=""></ion-nav-view>
</ion-tab>
</ion-tabs>
Take it more than an example of how to make it running and later use ionic framework the right way...Check that example here
Here is similar Q & A with an example using the named views (for sure better solution) ionic routing issue, shows blank page
Improved version with named views in a tab is here: http://plnkr.co/edit/Mj0rUxjLOXhHIelt249K?p=preview
<ion-tab title="Index" icon="icon ion-home" ui-sref="index">
<ion-nav-view name="index"></ion-nav-view>
</ion-tab>
<ion-tab title="Register" icon="icon ion-person" ui-sref="register">
<ion-nav-view name="register"></ion-nav-view>
</ion-tab>
targeting named views:
$stateProvider.state('index', {
url: '/',
views: { "index" : { templateUrl: "tpl.index.html" } },
parent: "app",
});
$stateProvider.state('register', {
url: "/register",
views: { "register" : { templateUrl: "tpl.register.html", } },
parent: "app",
});
You are correct in that it's not "right" to add files to the tags folder.
You've correctly guessed that copy
is the operation to use; it lets Subversion keep track of the history of these files, and also (I assume) store them much more efficiently.
In my experience, it's best to do copies ("snapshots") of entire projects, i.e. all files from the root check-out location. That way the snapshot can stand on its own, as a true representation of the entire project's state at a particular point in time.
This part of "the book" shows how the command is typically used.
You can use \D
which means non digits.
var removedText = self.val().replace(/\D+/g, '');
You could also use the HTML5 number input.
<input type="number" name="digit" />
const FindDate = (date, allDate) => {
// moment().diff only works on moment(). Make sure both date and elements in allDate array are in moment format
let nearestDate = -1;
allDate.some(d => {
const currentDate = moment(d)
const difference = currentDate.diff(d); // Or d.diff(date) depending on what you're trying to find
if(difference >= 0){
nearestDate = d
}
});
console.log(nearestDate)
}
The difference between an operating system and a kernel:
The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:
Most of these answers only address compile-time dependencies, but you'll find a host of NoClassDef exceptions at runtime. That's because you need more than the google-play-services.jar. It references resources that are part of the library project, and those are not included correctly if you only have the jar.
What worked best for me was to first get the project setup correctly in eclipse. Have your project structured so that it includes both your app and the library, as described here: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Multi-project-setup
Then export your app project from eclipse, and import into Android Studio as described here: http://developer.android.com/sdk/installing/migrate.html. Make sure to export both your app project and the google play services library project. When importing it will detect the library project and import it as a module. I just accepted all defaults during the project import process.
I resolved a similar problem by border-color: inherit
, see:
<li style="border-color: <?php echo $hex ?>;">...</li>
li {
border-width: 0;
}
li:before {
content: '';
display: inline-block;
float: none;
margin-right: 10px;
border-width: 4px;
border-style: solid;
border-color: inherit;
}
I think the upgrade of Java will not help. You need to uninstall the old version and then install the latest java version to help you. Make sure that you restart the computer once you are done with the installation.
Hope it helps!
Two's complement is a clever way of storing integers so that common math problems are very simple to implement.
To understand, you have to think of the numbers in binary.
It basically says,
Let's try it with a mini-byte of 4 bits (we'll call it a nibble - 1/2 a byte).
0000
- zero0001
- one0010
- two0011
- three0100
to 0111
- four to sevenThat's as far as we can go in positives. 23-1 = 7.
For negatives:
1111
- negative one1110
- negative two1101
- negative three1100
to 1000
- negative four to negative eightNote that you get one extra value for negatives (1000
= -8) that you don't for positives. This is because 0000
is used for zero. This can be considered as Number Line of computers.
Distinguishing between positive and negative numbers
Doing this, the first bit gets the role of the "sign" bit, as it can be used to distinguish between nonnegative and negative decimal values. If the most significant bit is 1
, then the binary can be said to be negative, where as if the most significant bit (the leftmost) is 0
, you can say the decimal value is nonnegative.
"Sign-magnitude" negative numbers just have the sign bit flipped of their positive counterparts, but this approach has to deal with interpreting 1000
(one 1
followed by all 0
s) as "negative zero" which is confusing.
"Ones' complement" negative numbers are just the bit-complement of their positive counterparts, which also leads to a confusing "negative zero" with 1111
(all ones).
You will likely not have to deal with Ones' Complement or Sign-Magnitude integer representations unless you are working very close to the hardware.
In case you don't have Linq, I solved it the following way:
private T[] GetArray<T>(IList<T> iList) where T: new()
{
var result = new T[iList.Count];
iList.CopyTo(result, 0);
return result;
}
Hope it helps
if you need in 2020
Objects.requireNonNull(getActivity()).onBackPressed();
I had an issue with the downscaleImage()
function posted above by @daniel-allen-langdon in that the image.width
and image.height
properties are not available immediately because the image load is asynchronous.
Please see updated TypeScript example below that takes this into account, uses async
functions, and resizes the image based on the longest dimension rather than just the width
function getImage(dataUrl: string): Promise<HTMLImageElement>
{
return new Promise((resolve, reject) => {
const image = new Image();
image.src = dataUrl;
image.onload = () => {
resolve(image);
};
image.onerror = (el: any, err: ErrorEvent) => {
reject(err.error);
};
});
}
export async function downscaleImage(
dataUrl: string,
imageType: string, // e.g. 'image/jpeg'
resolution: number, // max width/height in pixels
quality: number // e.g. 0.9 = 90% quality
): Promise<string> {
// Create a temporary image so that we can compute the height of the image.
const image = await getImage(dataUrl);
const oldWidth = image.naturalWidth;
const oldHeight = image.naturalHeight;
console.log('dims', oldWidth, oldHeight);
const longestDimension = oldWidth > oldHeight ? 'width' : 'height';
const currentRes = longestDimension == 'width' ? oldWidth : oldHeight;
console.log('longest dim', longestDimension, currentRes);
if (currentRes > resolution) {
console.log('need to resize...');
// Calculate new dimensions
const newSize = longestDimension == 'width'
? Math.floor(oldHeight / oldWidth * resolution)
: Math.floor(oldWidth / oldHeight * resolution);
const newWidth = longestDimension == 'width' ? resolution : newSize;
const newHeight = longestDimension == 'height' ? resolution : newSize;
console.log('new width / height', newWidth, newHeight);
// Create a temporary canvas to draw the downscaled image on.
const canvas = document.createElement('canvas');
canvas.width = newWidth;
canvas.height = newHeight;
// Draw the downscaled image on the canvas and return the new data URL.
const ctx = canvas.getContext('2d')!;
ctx.drawImage(image, 0, 0, newWidth, newHeight);
const newDataUrl = canvas.toDataURL(imageType, quality);
return newDataUrl;
}
else {
return dataUrl;
}
}
If you're putting a <meta> tag in your css files, you're doing something wrong. The <meta> tag belongs in your html files, and tells the browser how the html is encoded, it doesn't say anything about the css, which is a separate file. You could conceivably have completely different encodings for your html and css, although I can't imagine this would be a good idea.
you can try to download packages from mod
go get -v all
You can solve the problem by downloading the 'conveyor' library from extensions and update in Visual Studio.
You can access it from other devices.
Open Visual Studio
Tools > Extensions and Updates
Online > Visual Studio Marketplace
When you launch the API, you can access it from other devices. This plugin creates a link from your own ip address.
Example: https://youripadress:5000/api/values
var isAlaCarte =
ConfigurationManager.AppSettings.AllKeys.Contains("IsALaCarte") &&
bool.Parse(ConfigurationManager.AppSettings.Get("IsALaCarte"));
You must modify the query like this
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))
INSERT INTO #TMPGUARDIAN(FRST_NAME,LAST_NAME)
SELECT LAST_NAME,FRST_NAME FROM TBL_PEOPLE
-- Make a last session for clearing the all temporary tables. always drop at end. In your case, sometimes, there might be an error happen if the table is not exists, while you trying to delete.
DROP TABLE #TMPGUARDIAN
Avoid using insert into Because If you are using insert into then in future if you want to modify the temp table by adding a new column which can be filled after some process (not along with insert). At that time, you need to rework and design it in the same manner.
Use Table Variable http://odetocode.com/articles/365.aspx
declare @userData TABLE(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30)
)
Advantages No need for Drop statements, since this will be similar to variables. Scope ends immediately after the execution.
for macOS users: consider using .profile
instead of .bash_profile
. You may still need to manually add it to ~/.zshrc
:
source $HOME/.profile
Note that there is no such file by default! Quoting slhck https://superuser.com/a/473103:
Anyway, you can simply create the file if it doesn't exist and open it in a text editor.
touch ~/.profile open -e !$
The added value is that it feels good man to use a single file to set up the environment, regardless of the shell used. Loading a bash config file in zsh felt awkward.
Quoting an accepted answer by Cos https://stackoverflow.com/a/415444/2445063
.profile
is simply the login script filename originally used by/bin/sh
. bash, being generally backwards-compatible with/bin/sh
, will read.profile
if one exists
Following Filip Ekberg's research / opinion https://stackoverflow.com/a/415410/2445063
.profile
is the equivalent of.bash_profile
for the root. I think the name is changed to let other shells (csh, sh, tcsh) use it as well. (you don't need one as a user)
getting back to slhck, a note of attention regarding bash:
(…) once you create a file called
~/.bash_profile
, your~/.profile
will not be read anymore.
For this particular question, the standard suggestion of java.text.SimpleDateFormat
works, but has the unfortunate side effect that SimpleDateFormat
is not thread-safe and can be the source of particularly nasty problems since it'll corrupt your output in multi-threaded scenarios, and you won't get any exceptions!
I would strongly recommend looking at Joda for anything like this. Why ? It's a much richer and more intuitive time/date library for Java than the current library (and the basis of the up-and-coming new standard Java date/time library, so you'll be learning a soon-to-be-standard API).
This function has been serving me rather well recently:
action () {
# Test if the first parameter is non-zero
# and return straight away if so
if test $1 -ne 0
then
return $1
fi
# Discard the control parameter
# and execute the rest
shift 1
"$@"
local status=$?
# Test the exit status of the command run
# and display an error message on failure
if test ${status} -ne 0
then
echo Command \""$@"\" failed >&2
fi
return ${status}
}
You call it by appending 0 or the last return value to the name of the command to run, so you can chain commands without having to check for error values. With this, this statement block:
command1 param1 param2 param3...
command2 param1 param2 param3...
command3 param1 param2 param3...
command4 param1 param2 param3...
command5 param1 param2 param3...
command6 param1 param2 param3...
Becomes this:
action 0 command1 param1 param2 param3...
action $? command2 param1 param2 param3...
action $? command3 param1 param2 param3...
action $? command4 param1 param2 param3...
action $? command5 param1 param2 param3...
action $? command6 param1 param2 param3...
<<<Error-handling code here>>>
If any of the commands fail, the error code is simply passed to the end of the block. I find it useful when you don't want subsequent commands to execute if an earlier one failed, but you also don't want the script to exit straight away (for example, inside a loop).
You can use this method also it will act like that
thadari=[1,2,3,4,5,6]
#Front Two(Left)
print(thadari[:2])
[1,2]
#Last Two(Right)# edited
print(thadari[-2:])
[5,6]
#mid
mid = len(thadari) //2
lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]
Hope it will help
This is add new string in the file
using (var file = new StreamWriter(filePath + "log.txt", true))
{
file.WriteLine(log);
file.Close();
}
Just to make this absolutely clear for all:
A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.
This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.
To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.
To qualify the preferred naming conventions:
How about running the following from command line,
Devenv.exe /ResetSettings
You could also save those settings in to a file, like so,
Devenv.exe /ResetSettings "C:\My Files\MySettings.vssettings"
The /ResetSettings switch, Restores Visual Studio default settings. Optionally resets the settings to the specified .vssettings file.
The server sends the following in its response header to set a cookie field.
Set-Cookie:
name=
value
If there is a cookie set, then the browser sends the following in its request header.
Cookie:
name=
value
See the HTTP Cookie article at Wikipedia for more information.
I believe you're looking for...
import config.logging_settings # @UnusedImport
Note the double space before the comment to avoid hitting other formatting warnings.
Also, depending on your IDE (if you're using one), there's probably an option to add the correct ignore rule (e.g., in Eclipse, pressing Ctrl + 1, while the cursor is over the warning, will auto-suggest @UnusedImport
).
You can use
string extension = System.IO.Path.GetExtension(filename);
And then remove the extension manually:
string result = filename.Substring(0, filename.Length - extension.Length);
Usage
git clone <repository>
Clone the repository located at the <repository> onto the local machine. The original repository can be located on the local filesystem or on a remote machine accessible via HTTP or SSH.
git clone <repo> <directory>
Clone the repository located at <repository> into the folder called <directory> on the local machine.
Source: Setting up a repository
As of npm 5, npm will now save by default. In case,if you would like npm to work in a similar old fashion (no autosave) to how it was working in previous versions, you can update the config option to enable autosave as below.
npm config set save false
To get the current setting, you can execute the following command:
npm config get save
Show as decimal Select ifnull(format(100.00, 1, 'en_US'), 0) 100.0
Show as Percentage Select concat(ifnull(format(100.00, 0, 'en_US'), 0), '%') 100%
You can use this (based on here) :
public static boolean isPortrait(Activity activity) {
final int currentOrientation = getCurrentOrientation(activity);
return currentOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT || currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}
public static int getCurrentOrientation(Activity activity) {
//code based on https://www.captechconsulting.com/blog/eric-miles/programmatically-locking-android-screen-orientation
final Display display = activity.getWindowManager().getDefaultDisplay();
final int rotation = display.getRotation();
final Point size = new Point();
display.getSize(size);
int result;
if (rotation == Surface.ROTATION_0
|| rotation == Surface.ROTATION_180) {
// if rotation is 0 or 180 and width is greater than height, we have
// a tablet
if (size.x > size.y) {
if (rotation == Surface.ROTATION_0) {
result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
} else {
result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
}
} else {
// we have a phone
if (rotation == Surface.ROTATION_0) {
result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
} else {
result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
}
} else {
// if rotation is 90 or 270 and width is greater than height, we
// have a phone
if (size.x > size.y) {
if (rotation == Surface.ROTATION_90) {
result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
} else {
result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
}
} else {
// we have a tablet
if (rotation == Surface.ROTATION_90) {
result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
} else {
result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}
}
}
return result;
}
C++ is designed RAII in mind. There is really no better way to manage memory in C++ I think. But be careful not to allocate very big chunks (like buffer objects) on local scope. It can cause stack overflows and, if there is a flaw in bounds checking while using that chunk, you can overwrite other variables or return addresses, which leads to all kinds security holes.
My favorite function for entropy is the following:
def entropy(labels):
prob_dict = {x:labels.count(x)/len(labels) for x in labels}
probs = np.array(list(prob_dict.values()))
return - probs.dot(np.log2(probs))
I am still looking for a nicer way to avoid the dict -> values -> list -> np.array conversion. Will comment again if I found it.
You can use Guid.Empty
. It is a read-only instance of the Guid structure with the value of 00000000-0000-0000-0000-000000000000
you can also use these instead
var g = new Guid();
var g = default(Guid);
beware not to use Guid.NewGuid()
because it will generate a new Guid.
use one of the options above which you and your team think it is more readable and stick to it. Do not mix different options across the code. I think the Guid.Empty
is the best one since new Guid()
might make us think it is generating a new guid and some may not know what is the value of default(Guid)
.
Let me add an example here:
I'm trying to build Alluxio
on windows platform and got the same issue, it's because the pom.xml
contains below step:
<plugin>
<artifactId>exec-maven-plugin</artifactId>
<groupId>org.codehaus.mojo</groupId>
<inherited>false</inherited>
<executions>
<execution>
<id>Check that there are no Windows line endings</id>
<phase>compile</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>${build.path}/style/check_no_windows_line_endings.sh</executable>
</configuration>
</execution>
</executions>
</plugin>
The .sh
file is not executable on windows so the error throws.
Comment it out if you do want build Alluxio
on windows.
import { timer } from 'rxjs';
await timer(1000).pipe(take(1)).toPromise();
this works better for me
@Html.LabelFor(model => model.SomekingStatus, "foo bar")
its because of Headerfiles define what the class contains (Members, data-structures) and cpp files implement it.
And of course, the main reason for this is that you could include one .h File multiple times in other .h files, but this would result in multiple definitions of a class, which is invalid.
I was struggling with the same problem and found one solution. I guess it can help you.
when you run python manage.py runserver
, it will take 127.0.0.1 as default ip address and 8000 as default port number which can be configured in your python environment.
In your python setting, go to <your python env>\Lib\site-packages\django\core\management\commands\runserver.py
and set
1. default_port = '<your_port>'
2. find this under def handle and set
if not options.get('addrport'):
self.addr = '0.0.0.0'
self.port = self.default_port
Now if you run "python manage.py runserver" it will run by default on "0.0.0.0:
Enjoy coding .....
You should always use Keychain to store usernames and passwords, and since it's stored securely and only accessible to your app, there is no need to delete it when app quits (if that was your concern).
Apple provides sample code that stores, reads and deletes keychain items and here is how to use the keychain wrapper class from that sample which greatly simplifies using Keychain.
Include Security.framework (in Xcode 3 right-click on frameworks folder and add existing framework. In Xcode 4 select your project, then select target, go to Build Phases tab and click + under Link Binary With Files) and KeychainItemWrapper .h & .m files into your project, #import the .h file wherever you need to use keychain and then create an instance of this class:
KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"YourAppLogin" accessGroup:nil];
(YourAppLogin can be anything you chose to call your Keychain item and you can have multiple items if required)
Then you can set the username and password using:
[keychainItem setObject:@"password you are saving" forKey:kSecValueData];
[keychainItem setObject:@"username you are saving" forKey:kSecAttrAccount];
Get them using:
NSString *password = [keychainItem objectForKey:kSecValueData];
NSString *username = [keychainItem objectForKey:kSecAttrAccount];
Or delete them using:
[keychainItem resetKeychainItem];
function deleteEmpty(obj){
for(var k in obj)
if(k == "children"){
if(obj[k]){
deleteEmpty(obj[k]);
}else{
delete obj.children;
}
}
}
for(var i=0; i< a.children.length; i++){
deleteEmpty(a.children[i])
}
http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html
This is the greatest thing ever for learning VIM.
adjustsFontSizeToFit
and numberOfLines
works for me. They adjust long email into 1 line.
<View>
<Text
numberOfLines={1}
adjustsFontSizeToFit
style={{textAlign:'center',fontSize:30}}
>
{this.props.email}
</Text>
</View>
margin
to align images:Since we wanted the image
to be left-aligned
, we added:
img {
margin-right: auto;
}
Similarly for image
to be right-aligned
, we can add margin-right: auto;
. The snippet shows a demo for both types of alignment.
Good Luck...
div {_x000D_
display:flex; _x000D_
flex-direction:column;_x000D_
border: 2px black solid;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
text-align: center;_x000D_
}_x000D_
hr {_x000D_
border: 1px black solid;_x000D_
width: 100%_x000D_
}_x000D_
img.one {_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
img.two {_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div>_x000D_
<h1>Flex Box</h1>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<img src="https://via.placeholder.com/80x80" class="one" _x000D_
/>_x000D_
_x000D_
_x000D_
<img src="https://via.placeholder.com/80x80" class="two" _x000D_
/>_x000D_
_x000D_
<hr />_x000D_
</div>
_x000D_
If you want the ripple to be bounded to the size of the TextView/ImageView use:
<TextView
android:background="?attr/selectableItemBackground"
android:clickable="true"/>
(I think it looks better)
If parent dies, PPID of orphans change to 1 - you only need to check your own PPID. In a way, this is polling, mentioned above. here is shell piece for that:
check_parent () {
parent=`ps -f|awk '$2=='$PID'{print $3 }'`
echo "parent:$parent"
let parent=$parent+0
if [[ $parent -eq 1 ]]; then
echo "parent is dead, exiting"
exit;
fi
}
PID=$$
cnt=0
while [[ 1 = 1 ]]; do
check_parent
... something
done
It might help you!
SELECT DISTINCT
A.NAME AS OBJECT_NAME,
A.TYPE_DESC
FROM SYS.SQL_MODULES M
INNER JOIN SYS.OBJECTS A ON M.OBJECT_ID = A.OBJECT_ID
WHERE M.DEFINITION LIKE '%['+@SEARCH_TEXT+']%'
ORDER BY TYPE_DESC
Here i show you a snippet where your problem is solved (i know, it's been too long since you posted it, but i think this is cleaner than de "clear" fix)
#nav_x000D_
{_x000D_
float: left;_x000D_
width: 25%;_x000D_
height: 150px;_x000D_
background-color: #999;_x000D_
margin-bottom: 10px;_x000D_
}_x000D_
_x000D_
#content_x000D_
{_x000D_
float: left;_x000D_
margin-left: 1%;_x000D_
width: 65%;_x000D_
height: 150px;_x000D_
background-color: #999;_x000D_
margin-bottom: 10px;_x000D_
} _x000D_
#wrap_x000D_
{_x000D_
background-color:#DDD;_x000D_
overflow: hidden_x000D_
}
_x000D_
<div id="wrap">_x000D_
<h1>wrap1 </h1>_x000D_
<div id="nav"></div>_x000D_
<div id="content"><a href="index.htm">< Back to article</a></div>_x000D_
</div>
_x000D_
No, there's no Python-specific limit on the memory usage of a Python application. I regularly work with Python applications that may use several gigabytes of memory. Most likely, your script actually uses more memory than available on the machine you're running on.
In that case, the solution is to rewrite the script to be more memory efficient, or to add more physical memory if the script is already optimized to minimize memory usage.
Edit:
Your script reads the entire contents of your files into memory at once (line = u.readlines()
). Since you're processing files up to 20 GB in size, you're going to get memory errors with that approach unless you have huge amounts of memory in your machine.
A better approach would be to read the files one line at a time:
for u in files:
for line in u: # This will iterate over each line in the file
# Read values from the line, do necessary calculations
You can make your own "lifecycle methods" using hooks for maximum nostalgia.
Utility functions:
import { useEffect, useRef } from "react";
export const useComponentDidMount = handler => {
return useEffect(() => {
return handler();
}, []);
};
export const useComponentDidUpdate = (handler, deps) => {
const isInitialMount = useRef(true);
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
return;
}
return handler();
}, deps);
};
Usage:
import { useComponentDidMount, useComponentDidUpdate } from "./utils";
export const MyComponent = ({ myProp }) => {
useComponentDidMount(() => {
console.log("Component did mount!");
});
useComponentDidUpdate(() => {
console.log("Component did update!");
});
useComponentDidUpdate(() => {
console.log("myProp did update!");
}, [myProp]);
};
Take a look at "SET ROLE" and "SET SESSION AUTHORIZATION".
This is what I do... (terse and tested)
...
deleteDir(new File(dir_to_be_deleted));
...
// delete directory and contents
void deleteDir(File file) {
if (file.isDirectory())
for (String child : file.list())
deleteDir(new File(file, child));
file.delete(); // delete child file or empty directory
}
If you are using React, just do:
<input
value={this.state.input}
placeholder="Enter a number"
onChange={e => this.setState({ input: e.target.value.replace(/[^0-9]/g, '') })}
/>
<div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>_x000D_
<script type="text/babel">_x000D_
class Demo extends React.Component {_x000D_
state = {_x000D_
input: '',_x000D_
}_x000D_
_x000D_
onChange = e => {_x000D_
let input = e.target.value.replace(/[^0-9]/g, '');_x000D_
this.setState({ input });_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div>_x000D_
<input_x000D_
value={this.state.input}_x000D_
placeholder="Enter a number"_x000D_
onChange={this.onChange}_x000D_
/>_x000D_
<br />_x000D_
<h1>{this.state.input}</h1>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Demo />, document.getElementById('root'));_x000D_
</script>
_x000D_
I imagine that trygetvalue is doing something more like:
if(myDict.ReallyOptimisedVersionofContains(someKey))
{
someVal = myDict[someKey];
return true;
}
return false;
So hopefully no try/catch anywhere.
I think it is just a method of convenience really. I generally use it as it saves a line of code or two.
Intellij 2018.2.5
Run => Edit Configurations => Choose Node on the left hand side => expand Environment => Shorten Command line options => choose Classpath file or JAR manifest
For completeness, if you wanted to use replaceFirst, try this:
public static String cap1stChar(String userIdea)
{
String betterIdea = userIdea;
if (userIdea.length() > 0)
{
String first = userIdea.substring(0,1);
betterIdea = userIdea.replaceFirst(first, first.toUpperCase());
}
return betterIdea;
}//end cap1stChar
Verdaccio is what I was looking for and it deserves it's own answer ;) It is an actively maintained fork of Sinopia (highly upvoted answer here). It is a npm registry as a npm package, and can be found
here: https://github.com/verdaccio/verdaccio,
here: https://www.verdaccio.org,
and on port number: 4873
npm i -g verdaccio pm2
pm2 start --name verdaccio `which verdaccio`
pm2 save
docker run -it --rm --detach --name verdaccio -p 4873:4873 verdaccio/verdaccio
helm repo add verdaccio https://charts.verdaccio.org
helm repo update
helm install verdaccio/verdaccio
In WPF
apps This code working perfectly
private void txt1_KeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.IsKeyDown(Key.Enter) )
{
Button_Click(this, new RoutedEventArgs());
}
}
HTML:
<div class="bool-answer">
<div class="answer">Nej</div>
</div>
CSS:
.bool-answer {
border-radius: 50%;
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
}
I commonly use setdefault
for keyword argument dicts, such as in this function:
def notify(self, level, *pargs, **kwargs):
kwargs.setdefault("persist", level >= DANGER)
self.__defcon.set(level, **kwargs)
try:
kwargs.setdefault("name", self.client.player_entity().name)
except pytibia.PlayerEntityNotFound:
pass
return _notify(level, *pargs, **kwargs)
It's great for tweaking arguments in wrappers around functions that take keyword arguments.
Before pushing, do a git pull with rebase option. This will get the changes that you made online (in your origin) and apply them locally, then add your local changes on top of it.
git pull --rebase
Now, you can push to remote
git push
For more information take a look at Git rebase explained and Chapter 3.6 Git Branching - Rebasing.
To make a note on Dick's answer, this is correct, but I would not recommend using a For Each loop. For Each creates a temporary reference to the COM Cell behind the scenes that you do not have access to (that you would need in order to dispose of it).
See the following for more discussion:
How do I properly clean up Excel interop objects?
To illustrate the issue, try the For Each example, close your application, and look at Task Manager. You should see that an instance of Excel is still running (because all objects were not disposed of properly).
A cleaner way to handle this is to query the spreadsheet using ADO:
Try to use it:
window.onbeforeunload = function (event) {
var message = 'Important: Please click on \'Save\' button to leave this page.';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
$(function () {
$("a").not('#lnkLogOut').click(function () {
window.onbeforeunload = null;
});
$(".btn").click(function () {
window.onbeforeunload = null;
});
});
May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.
mysqldump --routines=true -u <user> my_database > my_database.sql
Meder Omuraliev suggested to use an event handler and set scrollTo(0,0). This is an example for Wassim-azirar. Bringing it all together, I assume this is the final solution.
We have 3 problems: the scrollbar, scrolling with mouse, and keyboard. This hides the scrollbar:
html, body{overflow:hidden;}
Unfortunally, you can still scroll with the keyboard: To prevent this, we can:
function keydownHandler(e) {
var evt = e ? e:event;
var keyCode = evt.keyCode;
if (keyCode==38 || keyCode==39 || keyCode==40 || keyCode==37){ //arrow keys
e.preventDefault()
scrollTo(0,0);
}
}
document.onkeydown=keydownHandler;
The scrolling with the mouse just naturally doesn't work after this code, so we have prevented the scrolling.
For example: https://jsfiddle.net/aL7pes70/1/
Since most sessions are stored in a COOKIE (as per the above comments and solutions) it is important to make sure the COOKIE is flagged as a SECURE one (front C#):
myHttpOnlyCookie.HttpOnly = true;
and/or vie php.ini (default TRUE since php 5.3):
session.cookie_httponly = True
def my_string = "some string"
println "here: " + my_string
Not quite sure why the answer above needs to go into benchmarks, string buffers, tests, etc.
jmh is a recent addition to OpenJDK and has been written by some performance engineers from Oracle. Certainly worth a look.
The jmh is a Java harness for building, running, and analysing nano/micro/macro benchmarks written in Java and other languages targetting the JVM.
Very interesting pieces of information buried in the sample tests comments.
See also:
In jQuery it would be as simple as $('#yourDivID').empty()
See the documentation.
I can think of one unfortunate side-effect. In java embedded databases, the number of ids you can have with a 32bit id field is 2^31, not 2^32 (~2billion, not ~4billion).
While I agree with the comments about passing in variables from your controller you can also register undefined functions when setting up the twig environment
$twig->registerUndefinedFunctionCallback(function ($name) {
// security
$allowed = false;
switch ($name) {
// example of calling a wordpress function
case 'get_admin_page_title':
$allowed = true;
break;
}
if ($allowed && function_exists($name)) {
return new Twig_Function_Function($name);
}
return false;
});
This is from the Twig recipe page
Haven't tried calling a function on an object as the original question requested
You should consider using an angular plug-in to handle the heavy lifting for you, unless you particularly enjoy typing hundreds of lines of knarly error prone ion-grid code. Simon Grimm has a cracking step by step tutorial that anyone can follow: https://devdactic.com/ionic-datatable-ngx-datatable/. This shows how to use ngx-datatable. But there are many other options (ng2-table is good).
The dead simple example goes like this:
<ion-content>
<ngx-datatable class="fullscreen" [ngClass]="tablestyle" [rows]="rows" [columnMode]="'force'" [sortType]="'multi'" [reorderable]="false">
<ngx-datatable-column name="Name"></ngx-datatable-column>
<ngx-datatable-column name="Gender"></ngx-datatable-column>
<ngx-datatable-column name="Age"></ngx-datatable-column>
</ngx-datatable>
</ion-content>
And the ts:
rows = [
{
"name": "Ethel Price",
"gender": "female",
"age": 22
},
{
"name": "Claudine Neal",
"gender": "female",
"age": 55
},
{
"name": "Beryl Rice",
"gender": "female",
"age": 67
},
{
"name": "Simon Grimm",
"gender": "male",
"age": 28
}
];
Since the original poster expressed their frustration of how difficult it is to achieve this with ion-grid, I think the correct answer should not be constrained by this as a prerequisite. You would be nuts to roll your own, given how good this is!
When you see this trying to push to github you may have to initialize this repo at github first: https://github.com/new.
1- There is no way to actually destroy an object in javascript, but using delete
, we could remove a reference from an object:
var obj = {};
obj.mypointer = null;
delete obj.mypointer;
2- The important point about the delete
keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The delete
keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.
3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have var array = [{}, {}]
overriding the value of the array like array = []
would remove the references to the two objects inside the array and those two objects would be marked as collectible.
4- for your solution the easiest way is just this:
var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;
As mentioned above, either setting storage.instance = null
or delete storage.instance
would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to null
then the storage object still has a property called instance (with the value null). If you delete storage.instance
then the storage object no longer has a property named instance.
and WHAT ABOUT destroy method ??
the paradoxical point here is if you use instance.destroy
in the destroy function you have no access to the actual instance
pointer, and it won't let you delete it.
The only way is to pass the reference to the destroy function and then delete it:
// Class constructor
var Class = function () {
this.destroy = function (baseObject, refName) {
delete baseObject[refName];
};
};
// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined
BUT if I were you I would simply stick to the first solution and delete the object like this:
storage.instance = null;
// OR
delete storage.instance;
WOW it was too much :)
I found a solution that when you scroll your window and end of a div shown from bottom gives you an alert.
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('.posts').offset().top + $('.posts').outerHeight() - window.innerHeight) {
alert('end reached');
}
});
In this example if you scroll down when div (.posts
) finish its give you an alert.
There is method U.fetch(url) in underscore-java library.
pom.xml:
<groupId>com.github.javadev</groupId>
<artifactId>underscore</artifactId>
<version>1.45</version>
Code example:
import com.github.underscore.lodash.U;
public class Download {
public static void main(String ... args) {
String text = U.fetch("https://stackoverflow.com/questions"
+ "/921262/how-to-download-and-save-a-file-from-internet-using-java").text();
}
}
I've had issue with IE7 and returning false before.
Check my answer here to another problem: Javascript not running on IE
a simple way would be to cast the dates into timestamps and take their difference and then extract the DAY part.
if you want real difference
select extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp);
if you want absolute difference
select abs(extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp));
Actually asXML() converts the string into xml as it name says:
<id>5</id>
This will display normally on a web page but it will cause problems when you matching values with something else.
You may use strip_tags function to get real value of the field like:
$newString = strip_tags($xml->asXML());
PS: if you are working with integers or floating numbers, you need to convert it into integer with intval() or floatval().
$newNumber = intval(strip_tags($xml->asXML()));
You may also want to use this to detect HTML 5 audio in some cases:
http://diveintohtml5.ep.io/everything.html
HTML 5 JS Detect function
function supportsAudio()
{
var a = document.createElement('audio');
return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
}
Max value for a particular column of a dataframe can be achieved by using -
your_max_value = df.agg({"your-column": "max"}).collect()[0][0]
i have resolved this by following steps.
1) Go to customise icon in the top right corner chrome.
2) click on
more tools option.
3) Click task manager.
4) Kill/end process GPU process
This has resolved my issue of black screen in chrome.
Check to make sure you are not mixing https:// with http://. Session variables do not flow between secure and insecure sessions.
If I'm not wrong, what you're trying to achieve is called Sticky navbar.
With a few lines of jQuery and the scroll event is pretty easy to achieve:
$(document).ready(function() {
var menu = $('.menu');
var content = $('.content');
var origOffsetY = menu.offset().top;
function scroll() {
if ($(window).scrollTop() >= origOffsetY) {
menu.addClass('sticky');
content.addClass('menu-padding');
} else {
menu.removeClass('sticky');
content.removeClass('menu-padding');
}
}
$(document).scroll();
});
I've done a quick working sample for you, hope it helps: http://jsfiddle.net/yeco/4EcFf/
To make it work with Bootstrap you only need to add or remove "navbar-fixed-top" instead of the "sticky" class in the jsfiddle .
You could modify you model to look like this:
$scope.options = {
"AL" : "Alabama",
"AK" : "Alaska",
"AS" : "American Samoa"
};
Then use
<select ng-options="k as v for (k,v) in options"></select>
I Think the simplest solutions is to add ngx-mask
npm i --save ngx-mask
then you can do
<input type='text' mask='(000) 000-0000' >
OR
<p>{{ phoneVar | mask: '(000) 000-0000' }} </p>
To round an integer to 1 significant figure the basic idea is to convert it to a floating point with 1 digit before the point and round that, then convert it back to its original integer size.
To do this we need to know the largest power of 10 less than the integer. We can use floor of the log 10 function for this.
from math import log10, floor def round_int(i,places): if i == 0: return 0 isign = i/abs(i) i = abs(i) if i < 1: return 0 max10exp = floor(log10(i)) if max10exp+1 < places: return i sig10pow = 10**(max10exp-places+1) floated = i*1.0/sig10pow defloated = round(floated)*sig10pow return int(defloated*isign)
As we also get this error when we use s3 NPM package. So the problem is with graceful-fs package we need to take it updated. It is working fine on 4.2.3.
So just look in what NPM package it is showing in logs trace and update the graceful-fs accordingly to 4.2.3.
This may be an old question but I have tried this method to remove query params. Seems to work smoothly for me as I needed a reload as well combined with removing of query params.
window.location.href = window.location.origin + window.location.pathname;
Also since I am using simple string addition operation I am guessing the performance will be good. But Still worth comparing with snippets in this answer
Enter the following command to insert data into the testlog table with some condition:
INSERT INTO TABLE testlog SELECT * FROM table1 WHERE some condition;
By using the List
property.
ListBox1.AddItem "foo"
ListBox1.List(ListBox1.ListCount - 1, 1) = "bar"
<table>
<tr>
<td>title</td>
<td>price</td>
<td>number</td>
</tr>
<? foreach ($shop as $row) : ?>
<tr>
<td><? echo $row[0]; ?></td>
<td><? echo $row[1]; ?></td>
<td><? echo $row[2]; ?></td>
</tr>
<? endforeach; ?>
</table>
read
reads until it finds a newline character or the end of file, and returns a non-zero exit code if it encounters an end-of-file. So it's quite possible for it to both read a line and return a non-zero exit code.
Consequently, the following code is not safe if the input might not be terminated by a newline:
while read LINE; do
# do something with LINE
done
because the body of the while
won't be executed on the last line.
Technically speaking, a file not terminated with a newline is not a text file, and text tools may fail in odd ways on such a file. However, I'm always reluctant to fall back on that explanation.
One way to solve the problem is to test if what was read is non-empty (-n
):
while read -r LINE || [[ -n $LINE ]]; do
# do something with LINE
done
Other solutions include using mapfile
to read the file into an array, piping the file through some utility which is guaranteed to terminate the last line properly (grep .
, for example, if you don't want to deal with blank lines), or doing the iterative processing with a tool like awk
(which is usually my preference).
Note that -r
is almost certainly needed in the read
builtin; it causes read
to not reinterpret \
-sequences in the input.
If Nothing else works try following
if (environment.production) {
// there is no need of this if block, angular internally creates following code structure when it sees --prod
// but at the time of writting this code, else block was not working in the production mode and NgModule metadata
// not found for AppModule error was coming at run time, added follow code to fix that, it can be removed probably
// when angular is upgraded to latest version or if it start working automatically. :)
// we could also avoid else block but building without --prod saves time in building app locally.
platformBrowser(extraProviders).bootstrapModuleFactory(<any>AppModuleNgFactory);
} else {
platformBrowserDynamic(extraProviders).bootstrapModule(AppModule);
}
Try this code
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById('errfn').innerHTML="this is invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input><div id="errfn"> </div>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
Go to "https://nodejs.org/en/" and then download either the latest or most stable versions. After downloading, Mac pkg installer updated the existing version. In linux: apt and windows installer will take care.
When I did the npm -v
from cmd it gave the most stable version which I have downloaded and installed from the above link.
xyz-MacBook-Pro:~ aasdfa$ node -v v8.11.1
Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
Becomes:
printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");
With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:
any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)
How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.
It stands indeed for whatever, as in whatever works for you
MVC vs MVVM vs MVP. What a controversial topic that many developers can spend hours and hours debating and arguing about.
For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it's now closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller.
Being able to categorize a framework and put it into one of the MV* buckets has some advantages. It can help developers get more comfortable with its apis by making it easier to create a mental model that represents the application that is being built with the framework. It can also help to establish terminology that is used by developers.
Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".
Angular gives you a lot of flexibility to nicely separate presentation logic from business logic and presentation state. Please use it fuel your productivity and application maintainability rather than heated discussions about things that at the end of the day don't matter that much.
I was getting same error while using WebServiceTemplate spring ws [err] org.springframework.ws.client.WebServiceTransportException: Cannot process the message because the content type 'text/xml; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8'. [415] [err] at org.springframework.ws.client.core.WebServiceTemplate.handleError(WebServiceTemplate.java:665). The WSDL which i was using has soap1.2 protocol and by default the protocol is soap1.1 . When i changed the protocol using below code, it was working
MessageFactory msgFactory = MessageFactory.newInstance(javax.xml.soap.SOAPConstants.SOAP_1_2_PROTOCOL);
SaajSoapMessageFactory saajSoapMessageFactory = new SaajSoapMessageFactory(msgFactory);
saajSoapMessageFactory.setSoapVersion(SoapVersion.SOAP_12);
getWebServiceTemplate().setMessageFactory(saajSoapMessageFactory);
The or
and and
python statements require truth
-values. For pandas
these are considered ambiguous so you should use "bitwise" |
(or) or &
(and) operations:
result = result[(result['var']>0.25) | (result['var']<-0.25)]
These are overloaded for these kind of datastructures to yield the element-wise or
(or and
).
Just to add some more explanation to this statement:
The exception is thrown when you want to get the bool
of a pandas.Series
:
>>> import pandas as pd
>>> x = pd.Series([1])
>>> bool(x)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
What you hit was a place where the operator implicitly converted the operands to bool
(you used or
but it also happens for and
, if
and while
):
>>> x or x
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> x and x
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> if x:
... print('fun')
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> while x:
... print('fun')
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Besides these 4 statements there are several python functions that hide some bool
calls (like any
, all
, filter
, ...) these are normally not problematic with pandas.Series
but for completeness I wanted to mention these.
In your case the exception isn't really helpful, because it doesn't mention the right alternatives. For and
and or
you can use (if you want element-wise comparisons):
>>> import numpy as np
>>> np.logical_or(x, y)
or simply the |
operator:
>>> x | y
>>> np.logical_and(x, y)
or simply the &
operator:
>>> x & y
If you're using the operators then make sure you set your parenthesis correctly because of the operator precedence.
There are several logical numpy functions which should work on pandas.Series
.
The alternatives mentioned in the Exception are more suited if you encountered it when doing if
or while
. I'll shortly explain each of these:
If you want to check if your Series is empty:
>>> x = pd.Series([])
>>> x.empty
True
>>> x = pd.Series([1])
>>> x.empty
False
Python normally interprets the len
gth of containers (like list
, tuple
, ...) as truth-value if it has no explicit boolean interpretation. So if you want the python-like check, you could do: if x.size
or if not x.empty
instead of if x
.
If your Series
contains one and only one boolean value:
>>> x = pd.Series([100])
>>> (x > 50).bool()
True
>>> (x < 50).bool()
False
If you want to check the first and only item of your Series (like .bool()
but works even for not boolean contents):
>>> x = pd.Series([100])
>>> x.item()
100
If you want to check if all or any item is not-zero, not-empty or not-False:
>>> x = pd.Series([0, 1, 2])
>>> x.all() # because one element is zero
False
>>> x.any() # because one (or more) elements are non-zero
True
I would like to show a little example on how is
and ==
are involved in immutable types. Try that:
a = 19998989890
b = 19998989889 +1
>>> a is b
False
>>> a == b
True
is
compares two objects in memory, ==
compares their values. For example, you can see that small integers are cached by Python:
c = 1
b = 1
>>> b is c
True
You should use ==
when comparing values and is
when comparing identities. (Also, from an English point of view, "equals" is different from "is".)
You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person
in this case. The default is to use std::less<T>
, which resolves to something equivalent to operator<
. This relies on it's own stored type having one. So if you were to implement
bool operator<(const Person& lhs, const Person& rhs);
it should work without any further changes. The implementation could be
bool operator<(const Person& lhs, const Person& rhs)
{
return lhs.age < rhs.age;
}
If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>
. For example,
struct LessThanByAge
{
bool operator()(const Person& lhs, const Person& rhs) const
{
return lhs.age < rhs.age;
}
};
then instantiate the queue like this:
std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;
Concerning the use of std::greater<Person>
as comparator, this would use the equivalent of operator>
and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator>
that can operate on two Person
instances.
My biggest concern with not checking folder node_modules into Git is that 10 years down the road, when your production application is still in use, npm may not be around. Or npm might become corrupted; or the maintainers might decide to remove the library that you rely on from their repository; or the version you use might be trimmed out.
This can be mitigated with repository managers like Maven, because you can always use your own local Nexus (Sonatype) or Artifactory to maintain a mirror with the packages that you use. As far as I understand, such a system doesn't exist for npm. The same goes for client-side library managers like Bower and Jam.js.
If you've committed the files to your own Git repository, then you can update them when you like, and you have the comfort of repeatable builds and the knowledge that your application won't break because of some third-party action.
I think that you are looking for something like this:
function rightclick() {
var rightclick;
var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert(rightclick); // true or false, you can trap right click here by if comparison
}
(http://www.quirksmode.org/js/events_properties.html)
And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >
when i click it the field does not get the focus. i can access the field via pressing the "tab-key"
It sounds like you've cancelled the default action for the mousedown event. Search through your HTML and JS for onmousedown handlers and look for a line that reads.
return false;
This line may be stopping you from focusing by clicking.
Re: your comment, I'm assuming you can't edit the code that adds this handler? If you can, the simplest solution is to just remove the return false;
statement.
is there a way to just add functionality to the event-trigger by not overwriting it?
That depends on how the handler is attached. If it's attached using the traditional registration method, e.g. element.onmousedown, then you could create a wrapper for it:
var oldFunc = element.onmousedown;
element.onmousedown = function (evt) {
oldFunc.call(this, evt || window.event);
}
Since this "wrapper" doesn't return false, it will not cancel the default action (focusing) for the element. If your event is attached using an advanced registration method, such as addEventListener or attachEvent then you could only remove the event handler using the function name/reference and reattach it with a wrapped function similar to the above. If it's an anonymous function that's added and you can't get a reference to it, then the only solution would be to attach another event handler and focus the element manually using the element.focus() method.
I assume you want to center them on one line and not on two separate lines based on your fiddle. If that is the case, try the following css:
div { background:red;
overflow:hidden;
}
span { display:block;
margin:0 auto;
width:200px;
}
span a { padding:5px 10px;
color:#fff;
background:#222;
}
I removed the float since you want to center it, and then made the span surrounding the links centered by adding margin:0 auto to them. Finally, I added a static width to the span. This centers the links on one line within the red div.
Quick fix:
position: relative;
top: -12px;
left: -2px;
this should balance out those offsets, but maybe you should take a look at your whole layout and see how that box interacts with other boxes.
As for terminology, left
, right
, top
and bottom
are CSS offset properties. They are used for positioning elements at a specific location (when used with absolute
or fixed
positioning), or to move them relative to their default location (when used with relative
positioning). Margins on the other hand specify gaps between boxes and they sometimes collapse, so they can't be reliably used as offsets.
But note that in your case that offset may not be computed (solely) from CSS offsets.
The first thing you should do is learn to read error messages. What does it tell you -- that you can't use two strings with the divide operator.
So, ask yourself why they are strings and how do you make them not-strings. They are strings because all input is done via strings. And the way to make then not-strings is to convert them.
One way to convert a string to an integer is to use the int function. For example:
percent = (int(pyc) / int(tpy)) * 100
To me, this is the most "natural" way to structure such data in JSON, provided that all of the keys are strings.
{
"keyvaluelist": {
"slide0001.html": "Looking Ahead",
"slide0008.html": "Forecast",
"slide0021.html": "Summary"
},
"otherdata": {
"one": "1",
"two": "2",
"three": "3"
},
"anotherthing": "thing1",
"onelastthing": "thing2"
}
I read this as
a JSON object with four elements
element 1 is a map of key/value pairs named "keyvaluelist",
element 2 is a map of key/value pairs named "otherdata",
element 3 is a string named "anotherthing",
element 4 is a string named "onelastthing"
The first element or second element could alternatively be described as objects themselves, of course, with three elements each.
I've faced this issue today. I am using Centos7, the solution was to install tomcat-admin-webapp package.
yum install tomcat-webapps tomcat-admin-webapps
You can either use the numerical indices ($row[0]
) or better, use AS
in the MySQL:
SELECT *, user.id AS user_id FROM ...
You can directly check the version with one line only by invoking PowerShell externally, such as from Command Prompt
powershell -Command "$PSVersionTable.PSVersion"
According to @psaul you can actually have one command that is agnostic from where it came (CMD, PowerShell or Pwsh). Thank you for that.
powershell -command "(Get-Variable PSVersionTable -ValueOnly).PSVersion"
I've tested and it worked flawlessly on both CMD and PowerShell.
Here's a point of view I haven't found in any of the other answers: use only one namespace. The main reason why namespaces are bad, according to most of the answers, is that you can have conflicting function names which can result in a total mess. However, this won't occur if you use only one namespace. Decide which library it is that you will use the most (maybe using namespace std;
) and stick with it.
One can think of it as having an invisible library prefix - std::vector
becomes just vector
. This, in my opinion, is the best of both worlds: on one hand it reduces the amount of typing you have to do (as intended by namespaces) and on the other, it still requires you to use the prefixes for clarity and security. If there's a function or object without a namespace prefix - you know it's from the one namespace you declared.
Just remember that if you will decide to use one globally - don't use others locally. This comes back to the other answers that local namespaces are often more useful than global ones since they provide variety in convenience.
It depends on wether the locatoin is detected by different DNS resolution from different locations, or by IP address that you are browsing from.
If its by DNS, you could just modify your hosts file to point at the server used in europe. Get your friend to ping the address, to see if its different from the one yours resolves to.
To browse from a different IP address:
You can rent a VPS server. You can use putty / SSH to act as a proxy. I use this from time to time to brows from the US using a VPS server I rent in the US.
Having an account on a remote host may or may not be enough. Sadly, my dreamhost account, even though I have ssh access, does not allow proxying.
Here are the common characters which need to be escaped in XML, starting with double quotes:
"
) are escaped to "
&
) is escaped to &
'
) are escaped to '
<
) is escaped to <
>
) is escaped to >
First of all, checked
can have a value of checked
, or an empty string.
$("input:checkbox").uniform();
$('#check1').live('click', function() {
$('#check2').attr('checked', 'checked').uniform();
});
There is some slight delay and jank as the font changes in the answer provided by Jason. Using the "change" event instead of "keyup" resolves this issue.
$('#iconified').on('change', function() {
var input = $(this);
if(input.val().length === 0) {
input.addClass('empty');
} else {
input.removeClass('empty');
}
});
I heartily recommended dbVis. The client runs on Mac, Windows and Linux and supports a variety of database servers, including PostgreSQL.
for $d in $doc/element2/element3
return fn:string-join(fn:data($d/element()), ".")
.
$doc stores the Xml.
sudo apt-get install libv4l-dev
Editing for RH based systems :
On a Fedora 16 to install pygame 1.9.1 (in a virtualenv):
sudo yum install libv4l-devel
sudo ln -s /usr/include/libv4l1-videodev.h /usr/include/linux/videodev.h
Analoguously to the two options (homebrew / manual) posted by @brismuth, here's the MacPorts way:
Install the Android SDK:
sudo port install android
Run the SDK manager:
sh /opt/local/share/java/android-sdk-macosx/tools/android
As @brismuth suggested, uncheck everything but Android SDK Platform-tools
(optional)
Install the packages, accepting licenses. Close the SDK Manager.
Add platform-tools
to your path; in MacPorts, they're in /opt/local/share/java/android-sdk-macosx/platform-tools
. E.g., for bash:
echo 'export PATH=$PATH:/opt/local/share/java/android-sdk-macosx/platform-tools' >> ~/.bash_profile
Refresh your bash profile (or restart your terminal/shell):
source ~/.bash_profile
Start using adb:
adb devices
my_module
is a folder not a module and you can't import a folder, try moving my_mod.py
to the same folder as the cool_script.py
and then doimport my_mod as mm
. This is because python only looks in the current directory and sys.path
, and so wont find my_mod.py
unless it's in the same directory
Or you can look here for an answer telling you how to import from other directories.
As to your other questions, I do not know as I do not use PyCharm.
I personally like to set up my analytics with the template URL instead of the current path. This is mainly because my application has many custom paths such as message/:id
or profile/:id
. If I were to send these paths, I'd have so many pages being viewed within analytics, it would be too difficult to check which page users are visiting most.
$rootScope.$on('$viewContentLoaded', function(event) {
$window.ga('send', 'pageview', {
page: $route.current.templateUrl.replace("views", "")
});
});
I now get clean page views within my analytics such as user-profile.html
and message.html
instead of many pages being profile/1
, profile/2
and profile/3
. I can now process reports to see how many people are viewing user profiles.
If anyone has any objection to why this is bad practise within analytics, I would be more than happy to hear about it. Quite new to using Google Analytics, so not too sure if this is the best approach or not.
Are you running on Linux? Perhaps the management agent is binding to localhost:
http://java.sun.com/j2se/1.5.0/docs/guide/management/faq.html#linux1
Just add C:\OpenCV2.0\bin
into your PATH environment variable
or
When you install OpenCV,
Choose the option, Add OpenCV to the system PATH for current user
which is not default one
If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P
even i came across the same situation and one of my mentor put this idea across to myself.
step:1 when clicked on the button on which we should show the drop down menu. then add the below class name "more_wrap_background" to the current active page like shown below
$('.ui-page-active').append("<div class='more_wrap_background' id='more-wrap-bg'> </div>");
step-2 then add a clicks for the div tag like
$(document).on('click', '#more-wrap-bg', hideDropDown);
where hideDropDown is the function to be called to hide drop down menu
Step-3 and important step while hiding the drop down menu is that remove that class you that added earlier like
$('#more-wrap-bg').remove();
I am removing by using its id in the above code
.more_wrap_background {
top: 0;
padding: 0;
margin: 0;
background: rgba(0, 0, 0, 0.1);
position: fixed;
display: block;
width: 100% !important;
z-index: 999;//should be one less than the drop down menu's z-index
height: 100% !important;
}
The simplest technique is to use NSString *uuid = [[NSProcessInfo processInfo] globallyUniqueString]
. See the NSProcessInfo class reference.
I'm using this function based on @Murph answer. It searches inside the current directory and lists the full path:
function findit
{
$filename = $args[0];
gci -recurse -filter "*${filename}*" -file -ErrorAction SilentlyContinue | foreach-object {
$place_path = $_.directory
echo "${place_path}\${_}"
}
}
Example usage: findit myfile
Two ways I know of:
export class SomeComponent implements OnInit
{
public localVar:any;
ngOnInit(){
this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
}
}
This will assign your result into local variable once information is returned just like in a promise. Then you just do {{ localVar }}
Another Way is to get a observable as a localVariable.
export class SomeComponent
{
public localVar:any;
constructor()
{
this.localVar = this.http.get(path).map(res => res.json());
}
}
This way you're exposing a observable at which point you can do in your html is to use AsyncPipe {{ localVar | async }}
Please try it out and let me know if it works. Also, since angular 2 is pretty new, feel free to comment if something is wrong.
Hope it helps
Keep a look out for SQL Server to support the 'INSERT ALL' Statement. Oracle has it already, it looks like this (SQL Cookbook):
insert all
when loc in ('NEW YORK', 'BOSTON') THEN
into dept_east(deptno, dname, loc) values(deptno, dname, loc)
when loc in ('CHICAGO') THEN
into dept_mid(deptno, dname, loc) values(deptno, dname, loc)
else
into dept_west(deptno, dname, loc) values(deptno, dname, loc)
select deptno, dname, loc
from dept
try ppretty:
from ppretty import ppretty
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
print ppretty(Animal(), seq_length=10)
Output:
__main__.Animal(age = 10, color = 'Spotted', kids = 0, legs = 2, name = 'Dog', smell = 'Alot')
You shouldn't need to let the users specify the margin on your website - Let them do it on their computer. Print dialogs usually (Adobe and Preview, at least) give you an option to scale and center the output on the printable area of the page:
Adobe
Preview
Of course, this assumes that you have computer literate users, which may or may not be the case.
If you want to convert string to variable inside body of function, but you want to have variable global:
test <- function() {
do.call("<<-",list("vartest","xxx"))
}
test()
vartest
[1] "xxx"
Usually the application that misses the .dll indicates what version you need – if one does not work, simply download the Microsoft visual C++ 2010 x86 or x64 from this link:
For 32 bit OS:Here
For 64 bit OS:Here
I recently ran into a problem with a UICommand not invoking in a JSF 1.2 application using IBM Extended Faces Components.
I had a command button on a row of a datatable (the extended version, so <hx:datatable>
) and the UICommand would not fire from certain rows from the table (the rows that would not fire were the rows greater than the default row display size).
I had a drop-down component for selecting number of rows to display. The value backing this field was in RequestScope
. The data backing the table itself was in a sort of ViewScope
(in reality, temporarily in SessionScope
).
If the row display was increased via the control which value was also bound to the datatable's rows
attribute, none of the rows displayed as a result of this change could fire the UICommand when clicked.
Placing this attribute in the same scope as the table data itself fixed the problem.
I think this is alluded to in BalusC #4 above, but not only did the table value need to be View or Session scoped but also the attribute controlling the number of rows to display on that table.
Is there some kind of query language ...
jq defines a JSON query language that is very similar to JSONPath -- see https://github.com/stedolan/jq/wiki/For-JSONPath-users
... [which] I can used to find an item in [0].objects where id = 3?
I'll assume this means: find all JSON objects under the specified key with id == 3, no matter where the object may be. A corresponding jq query would be:
.[0].objects | .. | objects | select(.id==3)
where "|" is the pipe-operator (as in command shell pipes), and where the segment ".. | objects" corresponds to "no matter where the object may be".
The basics of jq are largely obvious or intuitive or at least quite simple, and most of the rest is easy to pick up if you're at all familiar with command-shell pipes. The jq FAQ has pointers to tutorials and the like.
jq is also like SQL in that it supports CRUD operations, though the jq processor never overwrites its input. jq can also handle streams of JSON entities.
Two other criteria you might wish to consider in assessing a JSON-oriented query language are:
Your code is fine. What you are seeing is a linker issue.
If you put your code in a single file like this:
#include <iostream>
#include <string>
using namespace std;
string trim(const string& str)
{
size_t first = str.find_first_not_of(' ');
if (string::npos == first)
{
return str;
}
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last - first + 1));
}
int main() {
string s = "abc ";
cout << trim(s);
}
then do g++ test.cc
and run a.out, you will see it works.
You should check if the file that contains the trim
function is included in the link stage of your compilation process.
It seems that you want a list structure with very fast removal and random access by index (not by key) times. An ArrayList
gives you the latter and a HashMap
or TreeMap
give you the former.
There is one structure in Apache Commons Collections that may be what you are looking for, the TreeList. The JavaDoc specifies that it is optimized for quick insertion and removal at any index in the list. If you also need generics though, this will not help you.
I had trouble getting this to work and added another solution for anyone wanting/ needing to use FromCollection.
Instead of:
@Html.CheckBoxFor(model => true, item.TemplateId)
Format html helper like so:
@Html.CheckBoxFor(model => model.SomeProperty, new { @class = "form-control", Name = "SomeProperty"})
Then in the viewmodel/model wherever your logic is:
public void Save(FormCollection frm)
{
// to do instantiate object.
instantiatedItem.SomeProperty = (frm["SomeProperty"] ?? "").Equals("true", StringComparison.CurrentCultureIgnoreCase);
// to do and save changes in database.
}
holder.checkbox.setTag(row_id);
and
holder.checkbox.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
CheckBox c = (CheckBox) v;
int row_id = (Integer) v.getTag();
checkboxes.put(row_id, c.isChecked());
}
});
Need an edge-to-edge design? Drop the parent
.container
or.container-fluid
.
Still if you need to remove padding from .row
and immediate child columns you have to add the class .no-gutters
with the code from @Brian above to your own CSS file, actually it's Not 'right out of the box', check here for official details on the final Bootstrap 4 release: https://getbootstrap.com/docs/4.0/layout/grid/#no-gutters
There's also a <=>
operator:
SELECT pid FROM planets WHERE userid <=> NULL
Would work. The nice thing is that <=>
can also be used with non-NULL values:
SELECT NULL <=> NULL
yields 1
.
SELECT 42 <=> 42
yields 1
as well.
See here: https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#operator_equal-to
req.query
will return a JS object after the query string is parsed.
/user?name=tom&age=55 - req.query
would yield {name:"tom", age: "55"}
req.params
will return parameters in the matched route.
If your route is /user/:id and you make a request to /user/5 - req.params
would yield {id: "5"}
req.param
is a function that peels parameters out of the request. All of this can be found here.
UPDATE
If the verb is a POST
and you are using bodyParser
, then you should be able to get the form body in you function with req.body
. That will be the parsed JS version of the POST
ed form.
Python string objects are immutable. Example:
>>> a = 'tanim'
>>> 'Address of a is:{}'.format(id(a))
'Address of a is:64281536'
>>> a = 'ahmed'
>>> 'Address of a is:{}'.format(id(a))
'Address of a is:64281600'
In this example we can see that when we assign different value in a it doesn't modify.A new object is created.
And it can't be modified.
Example:
>>> a[0] = 'c'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
**TypeError**: 'str' object does not support item assignment
A error occurs.
Two solutions
1. use merge if you want to update the object
2. use save if you want to just save new object (make sure identity is null to let hibernate or database generate it)
3. if you are using mapping like
@OneToOne(fetch = FetchType.EAGER,cascade=CascadeType.ALL)
@JoinColumn(name = "stock_id")
Then use CascadeType.ALL to CascadeType.MERGE
thanks Shahid Abbasi
Completing Mr. Crocker's answer, be careful about ++ or -- operators or I don't know maybe other operators. They can affect the loop. for example I saw a code similar to this one in a course:
for(int i=0; i++*i<-1, i<3; printf(" %d", i));
The result would be $ 1 2$. So the first statement has affected the loop while the outcome of the following is lots of zeros.
for(int i=0; i<3; printf(" %d", i));
There are different ways of converting a string int value into an Integer data type value. You need to handle NumberFormatException for the string value issue.
Integer.parseInt
foo = Integer.parseInt(myString);
Integer.valueOf
foo = Integer.valueOf(myString);
Using Java 8 Optional API
foo = Optional.of(myString).map(Integer::parseInt).get();
Car.js
class Car {
getName() {return 'car'};
}
export default Car;
TestFile.js
const object = require('./Car.js');
const instance = new object();
error: TypeError: instance is not a constructor
printing content of object
object = {default: Car}
append default to the require function and it will work as contructor
const object = require('object-fit-images').default;
const instance = new object();
instance.getName();
You have to set the expiration date to delete cookies
Request.Cookies[yourCookie]?.Expires.Equals(DateTime.Now.AddYears(-1));
This won't throw an exception if the cookie doesn't exist.
Date format can also be set by using below query :-
alter SESSION set NLS_DATE_FORMAT = 'date_format'
e.g. : alter SESSION set NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS'
These steps worked for me on several Systems using Ubuntu 16.04, Apache 2.4, MariaDB, PDO
log into MYSQL as root
mysql -u root
Grant privileges. To a new user execute:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost';
FLUSH PRIVILEGES;
UPDATE for Google Cloud Instances
MySQL on Google Cloud seem to require an alternate command (mind the backticks).
GRANT ALL PRIVILEGES ON `%`.* TO 'newuser'@'localhost';
bind to all addresses:
The easiest way is to comment out the line in your /etc/mysql/mariadb.conf.d/50-server.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf file, depending on what system you are running:
#bind-address = 127.0.0.1
exit mysql and restart mysql
exit
service mysql restart
By default it binds only to localhost, but if you comment the line it binds to all interfaces it finds. Commenting out the line is equivalent to bind-address=*.
To check the binding of mysql service execute as root:
netstat -tupan | grep mysql
Well, the basic premise here is: no, it is not secure yet.
Basically, you can't run crypto in JavaScript: JavaScript Crypto Considered Harmful.
The problem is that you can't reliably get the crypto code into the browser, and even if you could, JS isn't designed to let you run it securely. So until browsers have a cryptographic container (which Encrypted Media Extensions provide, but are being rallied against for their DRM purposes), it will not be possible to do securely.
As far as a "Better way", there isn't one right now. Your only alternative is to store the data in plain text, and hope for the best. Or don't store the information at all. Either way.
Either that, or if you need that sort of security, and you need local storage, create a custom application...
go to the master branch our-team
pull all the new changes from our-team
branch
go to your branch featurex
featurex
merge the changes of our-team
branch into featurex
branch
our-team
{commit-hash}
if you want to merge specific commitspush your changes with the changes of our-team
branch
Note: probably you will have to fix conflicts after merging our-team
branch into featurex
branch before pushing
Please check permission "images/" directory
had better be
List
The only List
implementation in java.util.concurrent
is CopyOnWriteArrayList. There's also the option of a synchronized list as Travis Webb mentions.
That said, are you sure you need it to be a List
? There are a lot more options for concurrent Queue
s and Map
s (and you can make Set
s from Map
s), and those structures tend to make the most sense for many of the types of things you want to do with a shared data structure.
For queues, you have a huge number of options and which is most appropriate depends on how you need to use it:
You can make bar a function making it a method.
Foo.bar = function(passvariable){ };
As a property it would just be assigned a string, data type or boolean
Foo.bar = "a place";
My case Load From Server Example..
int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
if (jsonLength != 1) {
for (int i = 0; i < jsonLength; i++) {
JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
JSONObject resJson = (JSONObject) jsonArray.get(i);
//addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
}
Hope it help
The easiest and the cleanest way IMHO is :
q.data$number.of.a <- lengths(gregexpr('a', q.data$string))
# number string number.of.a`
#1 1 greatgreat 2`
#2 2 magic 1`
#3 3 not 0`
In addition to the other answers, asserts themselves throw exceptions, but only AssertionErrors. From a utilitarian standpoint, assertions aren't suitable for when you need fine grain control over which exceptions you catch.
Since .NET 4.7.1, you can use the side-effect free Prepend()
and Append()
. The output is going to be an IEnumerable.
// Creating an array of numbers
var ti = new List<int> { 1, 2, 3 };
// Prepend and Append any value of the same type
var results = ti.Prepend(0).Append(4);
// output is 0, 1, 2, 3, 4
Console.WriteLine(string.Join(", ", results ));
Here is a version, basically the same as a couple of the other answers, but that you can copy paste into your SQL server Management Studio to test, (and without generating any unwanted tables), thanks to some inline values.
WITH [TestData]([ID],[SKU],[PRODUCT]) AS
(
SELECT *
FROM (
VALUES
(1, 'FOO-23', 'Orange'),
(2, 'BAR-23', 'Orange'),
(3, 'FOO-24', 'Apple'),
(4, 'FOO-25', 'Orange')
)
AS [TestData]([ID],[SKU],[PRODUCT])
)
SELECT * FROM [TestData] WHERE [ID] IN
(
SELECT MIN([ID])
FROM [TestData]
GROUP BY [PRODUCT]
)
Result
ID SKU PRODUCT
1 FOO-23 Orange
3 FOO-24 Apple
I have ignored the following ...
WHERE ([SKU] LIKE 'FOO-%')
as its only part of the authors faulty code and not part of the question. It's unlikely to be helpful to people looking here.
a {
display: block;
position: relative;
}
I think that is all you need.
You can try like this. It works for me
$("#MISSION_ID").select2();
On hide/show or ajax request, we have to reinitialize the select2 plugin
For example:
$("#offialNumberArea").show();
$("#eventNameArea").hide();
$('.selectCriteria').change(function(){
var thisVal = $(this).val();
if(thisVal == 'sailor'){
$("#offialNumberArea").show();
$("#eventNameArea").hide();
}
else
{
$("#offialNumberArea").hide();
$("#eventNameArea").show();
$("#MISSION_ID").select2();
}
});
Working in bash 4 or higher version:
#!/bin/bash
echo "$0"; #"bash"
bash --version; #"GNU bash, version 5.0.3(1)-release (x86_64-pc-linux-gnu)"
In function:
echo $@; #"p1" "p2" "p3" "p4" "p5"
echo ${@: 0}; #"bash" "p1" "p2" "p3" "p4" "p5"
echo ${@: 1}; #"p1" "p2" "p3" "p4" "p5"
echo ${@: 2}; #"p2" "p3" "p4" "p5"
echo ${@: 2:1}; #"p2"
echo ${@: 2:2}; #"p2" "p3"
echo ${@: -2}; #"p4" "p5"
echo ${@: -2:1}; #"p4"
Notice the space between ':' and '-', otherwise it means different:
${var:-word} If var is null or unset,
word is substituted for var. The value of var does not change.${var:+word} If var is set,
word is substituted for var. The value of var does not change.
Which is described in:Unix / Linux - Shell Substitution
That problem happens when you try to access from a different domain or different port.
If you're using Visual Studio, then go to Tools > NuGet Package Manager > Package Manager Console. There you have to install the NuGet Package Microsoft.AspNet.WebApi.Cors
Install-Package Microsoft.AspNet.WebApi.Cors
Then, in PROJECT > App_Start > WebApiConfig, enable CORS
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//Enable CORS. Note that the domain doesn't have / in the end.
config.EnableCors(new EnableCorsAttribute("https://tiagoperes.eu",headers:"*",methods:"*"));
....
}
}
Once installed successfully, build the solution and that should suffice
If you're feeling brave, you can experiment with browser sniffing and get a version:
var ua = navigator.userAgent;
if(/chrome/i.test(ua)) {
var uaArray = ua.split(' ')
, version = uaArray[uaArray.length - 2].substr(7);
}
This detected version might be a Chrome version, or a Edge version, or something else. Browser plugins can easily change userAgent and platform and other things though, so this is not recommended.
Apologies to The Big Lebowski for using his answer within mine.
You can get just the edition name by using the following steps.
You can change the CSS color
property using JavaScript in the onclick
event handler (in the same way you change the value
property):
<input type="text" onclick="this.value=''; this.style.color='#000'" />
Note that it's not the best practice to use inline JavaScript. You'd be better off giving your input an ID, and moving your JavaScript out to a <script>
block instead:
document.getElementById("yourInput").onclick = function() {
this.value = '';
this.style.color = '#000';
}
If you have two lists called 'a' and 'b', you can do: [m - n for m,n in zip(a,b)]
Type "ctor" and press the TAB key twice this will add the default constructor automatically
In *nix systems, use the WHICH command to show the location of the mysqldump, try this :
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'test';
$mysqldump=exec('which mysqldump');
$command = "$mysqldump --opt -h $dbhost -u $dbuser -p $dbpass $dbname > $dbname.sql";
exec($command);
?>
$('#propertyType').on("click",function(e){
self.propertyTypeDialog = !self.propertyTypeDialog;
b = true;
e.stopPropagation();
console.log("input clicked");
});
$(document).on('click','body:not(#propertyType)',function (e) {
e.stopPropagation();
if(b == true) {
if ($(e.target).closest("#configuration").length == 0) {
b = false;
self.propertyTypeDialog = false;
console.log("outside clicked");
}
}
// console.log($(e.target).closest("#configuration").length);
});
Example:
You want to see all the items that are (round AND (red OR blue)):
{
"query": {
"bool": {
"must": [
{
"term": {"shape": "round"}
},
{
"bool": {
"should": [
{"term": {"color": "red"}},
{"term": {"color": "blue"}}
]
}
}
]
}
}
}
You can also do more complex versions of OR, for example if you want to match at least 3 out of 5, you can specify 5 options under "should" and set a "minimum_should" of 3.
Thanks to Glen Thompson and Sebastialonso for finding where my nesting wasn't quite right before.
Thanks also to Fatmajk for pointing out that "term" becomes "match" in ElasticSearch 6.
To get a fully independent copy of an object you can use the copy.deepcopy()
function.
For more details about shallow and deep copying please refer to the other answers to this question and the nice explanation in this answer to a related question.
To fix/install Android USB driver on Windows 7/8 32bit/64bit:
<sdk>\extras\google\usb_driver\
.)If it still doesn't work try changing from MTP to PTP.
Like the accepted answer well explained by lhunath, you can use
command > >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)
Beware than if you use bash you could have some issue.
Let me take the matthew-wilcoxson exemple.
And for those who "seeing is believing", a quick test:
(echo "Test Out";>&2 echo "Test Err") > >(tee stdout.log) 2> >(tee stderr.log >&2)
Personally, when I try, I have this result :
user@computer:~$ (echo "Test Out";>&2 echo "Test Err") > >(tee stdout.log) 2> >(tee stderr.log >&2)
user@computer:~$ Test Out
Test Err
Both message does not appear at the same level. Why Test Out
seem to be put like if it is my previous command ?
Prompt is on a blank line, let me think the process is not finished, and when I press Enter
this fix it.
When I check the content of the files, it is ok, redirection works.
Let take another test.
function outerr() {
echo "out" # stdout
echo >&2 "err" # stderr
}
user@computer:~$ outerr
out
err
user@computer:~$ outerr >/dev/null
err
user@computer:~$ outerr 2>/dev/null
out
Trying again the redirection, but with this function.
function test_redirect() {
fout="stdout.log"
ferr="stderr.log"
echo "$ outerr"
(outerr) > >(tee "$fout") 2> >(tee "$ferr" >&2)
echo "# $fout content :"
cat "$fout"
echo "# $ferr content :"
cat "$ferr"
}
Personally, I have this result :
user@computer:~$ test_redirect
$ outerr
# stdout.log content :
out
out
err
# stderr.log content :
err
user@computer:~$
No prompt on a blank line, but I don't see normal output, stdout.log content seem to be wrong, only stderr.log seem to be ok. If I relaunch it, output can be different...
So, why ?
Because, like explained here :
Beware that in bash, this command returns as soon as [first command] finishes, even if the tee commands are still executed (ksh and zsh do wait for the subprocesses)
So, if you use bash, prefer use the better exemple given in this other answer :
{ { outerr | tee "$fout"; } 2>&1 1>&3 | tee "$ferr"; } 3>&1 1>&2
It will fix the previous issues.
Now, the question is, how to retrieve exit status code ?
$?
does not works.
I have no found better solution than switch on pipefail with set -o pipefail
(set +o pipefail
to switch off) and use ${PIPESTATUS[0]}
like this
function outerr() {
echo "out"
echo >&2 "err"
return 11
}
function test_outerr() {
local - # To preserve set option
! [[ -o pipefail ]] && set -o pipefail; # Or use second part directly
local fout="stdout.log"
local ferr="stderr.log"
echo "$ outerr"
{ { outerr | tee "$fout"; } 2>&1 1>&3 | tee "$ferr"; } 3>&1 1>&2
# First save the status or it will be lost
local status="${PIPESTATUS[0]}" # Save first, the second is 0, perhaps tee status code.
echo "==="
echo "# $fout content :"
echo "<==="
cat "$fout"
echo "===>"
echo "# $ferr content :"
echo "<==="
cat "$ferr"
echo "===>"
if (( status > 0 )); then
echo "Fail $status > 0"
return "$status" # or whatever
fi
}
user@computer:~$ test_outerr
$ outerr
err
out
===
# stdout.log content :
<===
out
===>
# stderr.log content :
<===
err
===>
Fail 11 > 0
I found it... for (property in object) { // do stuff }
will list all the properties, and therefore all the globally declared variables on the window object..
In case if you want to implement your own Array.Copy method.
Static method which is of generic type.
static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
{
long totaltraversal = sourceIndex + copyNoOfElements;
long sourceArrayLength = sourceArray.Length;
//to check all array's length and its indices properties before copying
CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
for (long i = sourceIndex; i < totaltraversal; i++)
{
destinationArray[destinationIndex++] = sourceArray[i];
}
}
Boundary method implementation.
private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
{
if (sourceIndex >= sourceArray.Length)
{
throw new IndexOutOfRangeException();
}
if (copyNoOfElements > sourceArrayLength)
{
throw new IndexOutOfRangeException();
}
if (destinationArray.Length < copyNoOfElements)
{
throw new IndexOutOfRangeException();
}
}
It seems you are looking for the Post/Redirect/Get
pattern.
As another solution you may stop to use redirecting at all.
You may process and render the processing result at once with no POST
confirmation alert. You should just manipulate the browser history object:
history.replaceState("", "", "/the/result/page")
If I am understanding this correctly, you should be able to break the string into substrings to accomplish this.
i.e.:
string s = "this is a really long string" +
"and this is the rest of it";
Just a quick chime in here to hopefully help others... Especially with the newer version (since this is 2 years old)...
Instead of having some static fields defined in JS, you can also use the data-rule-*
attributes. You can use built-in rules as well as custom rules.
See http://jqueryvalidation.org/documentation/#link-list-of-built-in-validation-methods for built-in rules.
Example:
<p><label>Email: <input type="text" name="email" id="email" data-rule-email="true" required></label></p>
<p><label>Confirm Email: <input type="text" name="email" id="email_confirm" data-rule-email="true" data-rule-equalTo="#email" required></label></p>
Note the data-rule-*
attributes.
The lock event ID is 4800, and the unlock is 4801. You can find them in the Security logs. You probably have to activate their auditing using Local Security Policy (secpol.msc, Local Security Settings in Windows XP) -> Local Policies -> Audit Policy. For Windows 10 see the picture below.
Look in Description of security events in Windows 7 and in Windows Server 2008 R2 under Subcategory: Other Logon/Logoff Events.
LR is link register used to hold the return address for a function call.
SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.
From the ARM architecture reference:
SP, the Stack Pointer
Register R13 is used as a pointer to the active stack.
In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.
LR, the Link Register
Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.
When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:
• Return with a BX LR instruction.
• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...
A little improvement to Matthew's answer could be a lookahead instead of the last capturing group:
.replace(/(\w+)(\d+)(?=\w+)/, "$1!NEW_ID!");
Or you could split on the decimal and join with your new id like this:
.split(/\d+/).join("!NEW_ID!");
Example/Benchmark here: https://codepen.io/jogai/full/oyNXBX
Followed @hugh-pearse 's and @leszek-hanusz 's answers, with a little tweak. I had installed opencv from ubuntu 12.10 repository (libopencv-)* and had the same problem. Couldn't solve it with export OpenCV_DIR=/usr/share/OpenCV/
(since my OpenCVConfig.cmake whas there). It was solved when I also changed some lines on the OpenCVConfig.cmake file:
# ======================================================
# Include directories to add to the user project:
# ======================================================
# Provide the include directories to the caller
#SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")
SET(OpenCV_INCLUDE_DIRS "/usr/include/opencv;/usr/include/opencv2")
INCLUDE_DIRECTORIES(${OpenCV_INCLUDE_DIRS})
# ======================================================
# Link directories to add to the user project:
# ======================================================
# Provide the libs directory anyway, it may be needed in some cases.
#SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib")
SET(OpenCV_LIB_DIR "/usr/lib")
LINK_DIRECTORIES(${OpenCV_LIB_DIR})
And that worked on my Ubuntu 12.10. Remember to add the target_link_libraries(yourprojectname ${OpenCV_LIBS})
in your CMakeLists.txt.
Let's assume you have four cooks. In SOA, you assume they hate each other, so you strive to let them have to talk to each other as little as possible.
How do you do that? Well, you will first define the roles and interface -- cook 1 will make salad, cook 2 will make soup, cook 3 will make the steak, etc.. Then you will place the dishes well organised on the table (so these are the interfaces) and say, "Everybody please place your creation into your assigned dishes. Don't care about anybody else.".
This way, the four cooks have to talk to each other as little as possible, which is very good in software development -- not necessarily because they hate each other, but for other reasons like physical location, efficiency in making decisions etc.
It also means you can recombine the dishes (services) as you like. For example, you might just use the dessert to service a cafe, or just take the soup and combine it with a bread you bought from another company to provide a cheaper menu, or let other restaurants use your salads to combine with their dishes, etc.
One of the most successful implementation of SOA was at Amazon. Because of their design, they could re-package their whole infrastructure and sell it as Amazon Web Service.
*This is only one aspect of SOA.
Using multiple selections: select one pair of line breaks, then use Quick Find All (Alt+F3), or Quick Add Next (Ctrl+D) repeatedly, to select them all; then hit Enter to replace them with single line breaks.
def update(value, nvalue):
if not isinstance(value, dict) or not isinstance(nvalue, dict):
return nvalue
for k, v in nvalue.items():
value.setdefault(k, dict())
if isinstance(v, dict):
v = update(value[k], v)
value[k] = v
return value
use dict
or collections.Mapping
I suspect you're confused here because it's fundamentally confusing. To make things worse, the whole ours/theirs stuff switches roles (becomes backwards) when you are doing a rebase.
Ultimately, during a git merge
, the "ours" branch refers to the branch you're merging into:
git checkout merge-into-ours
and the "theirs" branch refers to the (single) branch you're merging:
git merge from-theirs
and here "ours" and "theirs" makes some sense, as even though "theirs" is probably yours anyway, "theirs" is not the one you were on when you ran git merge
.
While using the actual branch name might be pretty cool, it falls apart in more complex cases. For instance, instead of the above, you might do:
git checkout ours
git merge 1234567
where you're merging by raw commit-ID. Worse, you can even do this:
git checkout 7777777 # detach HEAD
git merge 1234567 # do a test merge
in which case there are no branch names involved!
I think it's little help here, but in fact, in gitrevisions
syntax, you can refer to an individual path in the index by number, during a conflicted merge
git show :1:README
git show :2:README
git show :3:README
Stage #1 is the common ancestor of the files, stage #2 is the target-branch version, and stage #3 is the version you are merging from.
The reason the "ours" and "theirs" notions get swapped around during rebase
is that rebase works by doing a series of cherry-picks, into an anonymous branch (detached HEAD mode). The target branch is the anonymous branch, and the merge-from branch is your original (pre-rebase) branch: so "--ours" means the anonymous one rebase is building while "--theirs" means "our branch being rebased".
As for the gitattributes entry: it could have an effect: "ours" really means "use stage #2" internally. But as you note, it's not actually in place at the time, so it should not have an effect here ... well, not unless you copy it into the work tree before you start.
Also, by the way, this applies to all uses of ours and theirs, but some are on a whole file level (-s ours
for a merge strategy; git checkout --ours
during a merge conflict) and some are on a piece-by-piece basis (-X ours
or -X theirs
during a -s recursive
merge). Which probably does not help with any of the confusion.
I've never come up with a better name for these, though. And: see VonC's answer to another question, where git mergetool
introduces yet more names for these, calling them "local" and "remote"!
The solution:
just change localhost for the IP of your PC
if you want to know this: Windows+r > cmd > ipconfig
example: http://192.168.0.107/directory/service/program.php?action=sendSomething
just replace 192.168.0.107 for your own IP (don't try 127.0.0.1 because it's same as localhost)
Here's the simple example.
diff --git a/file b/file
index 10ff2df..84d4fa2 100644
--- a/file
+++ b/file
@@ -1,5 +1,5 @@
line1
line2
-this line will be deleted
line4
line5
+this line is added
Here's an explanation (see details here).
--git
is not a command, this means it's a git version of diff (not unix)a/ b/
are directories, they are not real. it's just a convenience when we deal with the same file (in my case a/ is in index and b/ is in working directory)10ff2df..84d4fa2
are blob IDs of these 2 files100644
is the “mode bits,” indicating that this is a regular file (not executable and not a symbolic link)--- a/file +++ b/file
minus signs shows lines in the a/ version but missing from the b/ version; and plus signs shows lines missing in a/ but present in b/ (in my case --- means deleted lines and +++ means added lines in b/ and this the file in the working directory)@@ -1,5 +1,5 @@
in order to understand this it's better to work with a big file; if you have two changes in different places you'll get two entries like @@ -1,5 +1,5 @@
; suppose you have file line1 ... line100 and deleted line10 and add new line100 - you'll get:@@ -7,7 +7,6 @@ line6 line7 line8 line9 -this line10 to be deleted line11 line12 line13 @@ -98,3 +97,4 @@ line97 line98 line99 line100 +this is new line100
this.mainInput
doesn't actually point to anything. Since you are using a controlled component (i.e. the value of the input is obtained from state) you can set this.state.city
to null:
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({ city: '' });
}
h.chk.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
CheckBox chk=(CheckBox)view; // important line and code work
if(chk.isChecked())
{
Message.message(a,"Clicked at"+position);
}
else
{
Message.message(a,"UnClick");
}
}
});
Try this:
private void Button1_Click(Object sender, EventArgs e )
{
var myForm = new Form1();
myForm.Show();
}
As you can see in the Java Source of the java.lang.String class:
/**
* Allocates a new <code>String</code> that contains characters from
* a subarray of the character array argument. The <code>offset</code>
* argument is the index of the first character of the subarray and
* the <code>count</code> argument specifies the length of the
* subarray. The contents of the subarray are copied; subsequent
* modification of the character array does not affect the newly
* created string.
*
* @param value array that is the source of characters.
* @param offset the initial offset.
* @param count the length.
* @exception IndexOutOfBoundsException if the <code>offset</code>
* and <code>count</code> arguments index characters outside
* the bounds of the <code>value</code> array.
*/
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = new char[count];
this.count = count;
System.arraycopy(value, offset, this.value, 0, count);
}
Parameter references are surrounded by <code></code>
tags, which means that the Javadoc syntax does not provide any way to do such a thing. (I think String.class is a good example of javadoc usage).
I am giving one exapmle to undersand when do we use @Queryparam
and @pathparam
For example I am taking one resouce is carResource
class
If you want to make the inputs of your resouce method manadatory then use the param type as @pathaparam
, if the inputs of your resource method should be optional then keep that param type as @QueryParam
param
@Path("/car")
class CarResource
{
@Get
@produces("text/plain")
@Path("/search/{carmodel}")
public String getCarSearch(@PathParam("carmodel")String model,@QueryParam("carcolor")String color) {
//logic for getting cars based on carmodel and color
-----
return cars
}
}
For this resouce pass the request
req uri ://address:2020/carWeb/car/search/swift?carcolor=red
If you give req like this the resouce will gives the based car model and color
req uri://address:2020/carWeb/car/search/swift
If you give req like this the resoce method will display only swift model based car
req://address:2020/carWeb/car/search?carcolor=red
If you give like this we will get ResourceNotFound exception because in the car resouce class I declared carmodel as @pathPram
that is you must and should give the carmodel as reQ uri otherwise it will not pass the req to resouce but if you don't pass the color also it will pass the req to resource why because the color is @quetyParam
it is optional in req.
string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>(); foreach (var line in lines) { string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); list1.Add(values[0]); list2.Add(values[1]); }
The comments referring to blocks and Procs are correct in that they are more usual in Ruby. But you can pass a method if you want. You call method
to get the method and .call
to call it:
def weightedknn( data, vec1, k = 5, weightf = method(:gaussian) )
...
weight = weightf.call( dist )
...
end