You should have a 'skeleton' somewhere in /etc
, probably /etc/skeleton
, or check the default settings, probably /etc/default
or something. Those are scripts that define standard environment variables getting set during a login.
If it is just for your own account: check the (hidden) file ~/.profile
and ~/.login
. Or generate them, if they don't exist. These are also evaluated by the login process.
Better to turn on core dump programmatically using system call setrlimit
.
example:
#include <sys/resource.h>
bool enable_core_dump(){
struct rlimit corelim;
corelim.rlim_cur = RLIM_INFINITY;
corelim.rlim_max = RLIM_INFINITY;
return (0 == setrlimit(RLIMIT_CORE, &corelim));
}
I created a solution using pipes, eval and signal.
parent() {
if [ -z "$G_EVAL_FD" ]; then
die 1 "Rode primeiro parent_setup no processo pai"
fi
if [ $(ppid) = "$$" ]; then
"$@"
else
kill -SIGUSR1 $$
echo "$@">&$G_EVAL_FD
fi
}
parent_setup() {
G_EVAL_FD=99
tempfile=$(mktemp -u)
mkfifo "$tempfile"
eval "exec $G_EVAL_FD<>'$tempfile'"
rm -f "$tempfile"
trap "read CMD <&$G_EVAL_FD; eval \"\$CMD\"" USR1
}
parent_setup #on parent shell context
( A=1 ); echo $A # prints nothing
( parent A=1 ); echo $A # prints 1
It might work with any command.
The solutions given here fail on either directories or symlinks (or both). On Linux, you can test files, directories and symlinks with:
if [[ -f "$file" && -x $(realpath "$file") ]]; then .... fi
On OS X, you should be able to install coreutils with homebrew and use grealpath
.
isexec
functionYou can define a function for convenience:
isexec() {
if [[ -f "$1" && -x $(realpath "$1") ]]; then
true;
else
false;
fi;
}
Or simply
isexec() { [[ -f "$1" && -x $(realpath "$1") ]]; }
Then you can test using:
if `isexec "$file"`; then ... fi
Eric's answer helpfully explains that the trouble comes from comparing a Pandas Series (containing a NumPy array) to a Python string. Unfortunately, his two workarounds both just suppress the warning.
To write code that doesn't cause the warning in the first place, explicitly compare your string to each element of the Series and get a separate bool for each. For example, you could use map
and an anonymous function.
myRows = df[df['Unnamed: 5'].map( lambda x: x == 'Peter' )].index.tolist()
Booleans default value is false only for classes' fields. If within a method, you have to initialize your variable by true or false. Thus for example in your case, you'll have a compilation error.
Moreover, I don't really get the point, but the only way to enter within a if is to evaluate the condition to true.
You must create a migration, where you will specify default value for a new field, since you don't want it to be null. If null is not required, simply add null=True
and create and run migration.
Just as Martin Konecny's answer said, you need to change the versionCode to something higher.
Your previous version code was 28
. it should be changed to 29
.
According to the document on the android developer website. a version code is
An integer value that represents the version of the application code, relative to other versions.
So it should be related(by related I mean higher) to the previous versionCode as noted by the document:
you should make sure that each successive release of your application uses a greater value.
As mentioned again in the document
the android:versionCode value does not necessarily have a strong resemblance to the application release version that is visible to the user (see android:versionName, below)
So even though this is the release 2.0001
of your app, it does not necessarily mean that the versionCode is 2
.
Hope this helps :)
This solution works for matplotlib versions 3.0.1, 3.0.3 and 3.2.1.
def save_inp_as_output(_img, c_name, dpi=100):
h, w, _ = _img.shape
fig, axes = plt.subplots(figsize=(h/dpi, w/dpi))
fig.subplots_adjust(top=1.0, bottom=0, right=1.0, left=0, hspace=0, wspace=0)
axes.imshow(_img)
axes.axis('off')
plt.savefig(c_name, dpi=dpi, format='jpeg')
Because the subplots_adjust setting makes the axis fill the figure, you don't want to specify a bbox_inches='tight', as it actually creates whitespace padding in this case. This solution works when you have more than 1 subplot also.
You could do something like this if you wanted
package main
import "fmt"
type Pair struct {
a, b interface{}
}
func main() {
p1 := Pair{"finished", 42}
p2 := Pair{6.1, "hello"}
fmt.Println("p1=", p1, "p2=", p2)
fmt.Println("p1.b", p1.b)
// But to use the values you'll need a type assertion
s := p1.a.(string) + " now"
fmt.Println("p1.a", s)
}
However I think what you have already is perfectly idiomatic and the struct describes your data perfectly which is a big advantage over using plain tuples.
transient
is the solution for me. thanks! it's native to Java and avoids you to add another framework-specific annotation.
I'm using this function that find all images in my letter and attaches it to the message.
Parameters: Takes your HTML (which you want to send);
Return: The necessary HTML and headers, which you can use in mail()
;
Example usage:
define("DEFCALLBACKMAIL", "[email protected]"); // WIll be shown as "from".
$final_msg = preparehtmlmail($html); // give a function your html*
mail('[email protected]', 'your subject', $final_msg['multipart'], $final_msg['headers']);
// send email with all images from html attached to letter
function preparehtmlmail($html) {
preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
$i = 0;
$paths = array();
foreach ($matches[1] as $img) {
$img_old = $img;
if(strpos($img, "http://") == false) {
$uri = parse_url($img);
$paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
$content_id = md5($img);
$html = str_replace($img_old,'cid:'.$content_id,$html);
$paths[$i++]['cid'] = $content_id;
}
}
$boundary = "--".md5(uniqid(time()));
$headers .= "MIME-Version: 1.0\n";
$headers .="Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
$headers .= "From: ".DEFCALLBACKMAIL."\r\n";
$multipart = '';
$multipart .= "--$boundary\n";
$kod = 'utf-8';
$multipart .= "Content-Type: text/html; charset=$kod\n";
$multipart .= "Content-Transfer-Encoding: Quot-Printed\n\n";
$multipart .= "$html\n\n";
foreach ($paths as $path) {
if(file_exists($path['path']))
$fp = fopen($path['path'],"r");
if (!$fp) {
return false;
}
$imagetype = substr(strrchr($path['path'], '.' ),1);
$file = fread($fp, filesize($path['path']));
fclose($fp);
$message_part = "";
switch ($imagetype) {
case 'png':
case 'PNG':
$message_part .= "Content-Type: image/png";
break;
case 'jpg':
case 'jpeg':
case 'JPG':
case 'JPEG':
$message_part .= "Content-Type: image/jpeg";
break;
case 'gif':
case 'GIF':
$message_part .= "Content-Type: image/gif";
break;
}
$message_part .= "; file_name = \"$path\"\n";
$message_part .= 'Content-ID: <'.$path['cid'].">\n";
$message_part .= "Content-Transfer-Encoding: base64\n";
$message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
$message_part .= chunk_split(base64_encode($file))."\n";
$multipart .= "--$boundary\n".$message_part."\n";
}
$multipart .= "--$boundary--\n";
return array('multipart' => $multipart, 'headers' => $headers);
}
I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.
int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
for(int i=0; i<=names.size()-1; ++i) {
if(names[i]==req_name){
cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
return 0;
}
else if(names[i]!=req_name && i==names.size()-1) {
cout<<"That name is not an element in this vector"<<'\n';
} else {
continue;
}
}
You may start with Titanium for desktop dev. Also you may have a look at Chromium Embedded Framework. It's basically a web browser control based on chromium.
It's written in C++ so you can do all the low level OS stuff you want(Growl, tray icons, local file access, com ports, etc) in your container app, and then all the application logic and gui in html/javascript. It allows you to intercept any http request to either serve local resources or perform some custom action. For example, a request to http://localapp.com/SetTrayIconState?state=active could be intercepted by the container and then call the C++ function to update the tray icon.
It also allows you to create functions that can be called directly from JavaScript.
It's very difficult to debug JavaScript directly in CEF. There's no support for anything like Firebug.
You may also try AppJS.com (Helps to build Desktop Applications. for Linux, Windows and Mac using HTML, CSS and JavaScript)
Also, as pointed out by @Clint, the team at brackets.io (Adobe) created an awesome shell using Chromium Embedded Framework that makes it much easier to get started. It is called the brackets shell: github.com/adobe/brackets-shell Find out more about it here: clintberry.com/2013/html5-desktop-apps-with-brackets-shell
You can try using
org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(yourCollection);
This would do it.
public static void main(String[] args) {
double d = 12.349678;
int r = (int) Math.round(d*100);
double f = r / 100.0;
System.out.println(f);
}
You can short this method, it's easy to understand that's why I have written like this.
Suppose you wanted to cast a String
to a File
(yes it does not make any sense), you cannot cast it directly because the File
class is not a child and not a parent of the String
class (and the compiler complains).
But you could cast your String
to Object
, because a String
is an Object
(Object
is parent). Then you could cast this object to a File
, because a File is an Object
.
So all you operations are 'legal' from a typing point of view at compile time, but it does not mean that it will work at runtime !
File f = (File)(Object) "Stupid cast";
The compiler will allow this even if it does not make sense, but it will crash at runtime with this exception:
Exception in thread "main" java.lang.ClassCastException:
java.lang.String cannot be cast to java.io.File
The default import method is already "relative", from the PYTHONPATH. The PYTHONPATH is by default, to some system libraries along with the folder of the original source file. If you run with -m to run a module, the current directory gets added to the PYTHONPATH. So if the entry point of your program is inside of Proj, then using import Common.Common
should work inside both Server.py and Client.py.
Don't do a relative import. It won't work how you want it to.
The right way to change directory or run from multiple directories under different port for Apache 2 is as follows:
For Apache 2, the configuration files are located under /etc/apache2
and doesn’t use a single configuration file as in older versions but is split into smaller configuration files, with /etc/apache2/apache2.conf
being the main configuration file. To serve files from a different directory we need a new virtualhost conf file. The virtualhost configuration files are located in /etc/apache2/sites-available
(do not edit files within sites-enabled). The default Apache installation uses virtualhost conf file 000-default.conf
.
Start by creating a new virtualhost file by copying the default virtualhost file used by the default installation of Apache (the one that runs at localhost on port 80). Change into directory /etc/apache2/sites-available
and then make copy by sudo cp 000-default.conf example.com.conf
, now edit the file by sudo gedit example.com.conf
to:
<VirtualHost *:80>
ServerAdmin example@localhost
DocumentRoot /home/ubuntu/example.com
</VirtualHost>
I have deleted the nonimportant lines from the above file for brevity. Here DocumentRoot
is the path to the directory from which the website files are to be served such as index.html
.
Create the directory from which you want to serve the files, for example, mkdir example.com
and change owner and default group of the directory, for example, if your logged in user name is ubuntu
change permissions as sudo chown ubuntu:www-data example.com
. This grants full access to the user ubuntu
and allows read and execute access to the group www-data
.
Now edit the Apache configuration file /etc/apache2/apache2.conf
by issuing command sudo gedit apache2.conf
and find the line <Directory /var/www/>
and below the closing tag </Directory>
, add the following below:
<Directory /home/ubuntu/example.com>
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
</Directory>
Now there are two commands to enable or disable the virtualhost configuration files, which are a2ensite
and a2dissite
respectively. Now since our example.com.conf
file uses the same port(80
) as used by the default configuration file(000-default.conf
), we have to disable the default configuration file by issuing the command sudo a2dissite 000-default.conf
and enable our virtualhost configuration file by sudo a2ensite example.com.conf
Now restart or reload the server with command sudo service apache2 restart
. Now Apache serves files from directory example.com
at localhost
on default port of 80
.
The a2ensite
command basically creates a symbolic link to the configuration file under the site-enabled directory.
Do not edit files within sites-enabled (or *-enabled) directory, as pointed out in this answer.
Now if you need to run the directory on a different port, change the port number from 80 to 8080 by editing the virtualhost file as:
<VirtualHost *:8080>
ServerAdmin user@localhost
DocumentRoot /home/ubuntu/work
</VirtualHost>
and editing /etc/apache2/ports.conf
and adding Listen 8080
just below the line Listen 80
Now we can enable the default virtualhost configuration file that runs on port 80 since example.com directory uses port 8080, as sudo a2ensite 000-default.conf
.
Now restart or reload the server with command sudo service apache2 restart
. Now both the directories can be accessed from localhost
and localhost:8080
.
if you check null or empty String so you can try this
if (createReminderRequest.getDate() == null && createReminderRequest.getDate().trim().equals("")){
DialogUtility.showToast(this, ProjectUtils.getString(R.string.please_select_date_n_time));
}
Subclass your textfields... and also textviews
In the subclass put this code..
-(void)conformsToKeyboardDismissNotification{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissKeyBoard) name:KEYBOARD_DISMISS object:nil];
}
-(void)deConformsToKeyboardDismissNotification{
[[NSNotificationCenter defaultCenter] removeObserver:self name:KEYBOARD_DISMISS object:nil];
}
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self resignFirstResponder];
}
In the textfield delegates (similarly for textview delegates)
-(void)textFieldDidBeginEditing:(JCPTextField *)textField{
[textField conformsToKeyboardDismissNotification];
}
- (void)textFieldDidEndEditing:(JCPTextField *)textField{
[textField deConformsToKeyboardDismissNotification];
}
All set.. Now just post the notification from anywhere in your code. It will resign any keyboard.
You can use it by using the StackTrace
and then you can get reflective types from that.
StackTrace stackTrace = new StackTrace(); // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
StackFrame callingFrame = stackFrames[1];
MethodInfo method = callingFrame.GetMethod();
Console.Write(method.Name);
Console.Write(method.DeclaringType.Name);
I'm not sure that Java has infinity for every numerical type but for some numerical data types the answer is positive:
Float.POSITIVE_INFINITY
Float.NEGATIVE_INFINITY
or
Double.POSITIVE_INFINITY
Double.NEGATIVE_INFINITY
Also you may find useful the following article which represents some mathematical operations involving +/- infinity: Java Floating-Point Number Intricacies.
If you are still intrested in why this didn't work for you at first:
The reason you don't see changes you've made to the cell's style is because you do these changes before the form was shown, and so they are disregarded.
Changing cell styles in the events suggested here will do the job, but they are called multiple times causing your style changes to happen more times than you wish, and so aren't very efficient.
To solve this, either change the style after the point in your code in which the form is shown, or subscribe to the Shown event, and place your changes there (this is event is called significantly less than the other events suggested).
As clarified in your comment, Spacemoses, you stated an example: WHERE (Note is null) ^ (ID is null). I do not see why you chose to accept any answer given here as answering that. If i needed an xor for that, i think i'd have to use the AND/OR equivalent logic:
WHERE (Note is null and ID is not null) OR (Note is not null and ID is null)
That is equivalent to:
WHERE (Note is null) XOR (ID is null)
when 'XOR' is not available.
You can use the following function:
DESCRIBE TABLE <itab-Name> LINES <variable>
After the call, variable contains the number of rows of the internal table .
Open the Servers view -> double click tomcat -> drop down the Timeouts section
There you can increase the startup time for each particular server.
Use the Apache BooleanUtils.
(If peak performance is the most important priority in your project then look at one of the other answers for a native solution that doesn't require including an external library.)
Don't reinvent the wheel. Leverage what's already been built and use isTrue()
:
BooleanUtils.isTrue( bool );
Checks if a Boolean
value is true, handling null
by returning false
.
If you're not limited to the libraries you're "allowed" to include, there are a bunch of great helper functions for all sorts of use-cases, including Booleans
and Strings
. I suggest you peruse the various Apache libraries and see what they already offer.
I believe it's included even in Edu version. Just right click the solid green arrow button (Run) and choose "Add parameters".
Why not add "display: none;" to the divs style attribute? Thats all JQuery's .hide() function does.
Here is a late answer, just for simplistic approach using Int()
and If
in case of 1-3 character columns:
Function outColLetterFromNumber(i As Integer) As String
If i < 27 Then 'one-letter
col = Chr(64 + i)
ElseIf i < 677 Then 'two-letter
col = Chr(64 + Int(i / 26)) & Chr(64 + i - (Int(i / 26) * 26))
Else 'three-letter
col = Chr(64 + Int(i / 676)) & Chr(64 + Int(i - Int(i / 676) * 676) / 26)) & Chr(64 + i - (Int(i - Int(i / 676) * 676) / 26) * 26))
End If
outColLetterFromNumber = col
End Function
curl's --data
will by default send Content-Type: application/x-www-form-urlencoded
in the request header. However, when using Postman's raw
body mode, Postman sends Content-Type: text/plain
in the request header.
So to achieve the same thing as Postman, specify -H "Content-Type: text/plain"
for curl:
curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network
tab :
During the focus event you can scroll past the document height and magically the window.innerHeight is reduced by the height of the virtual keyboard. Note that the size of the virtual keyboard is different for landscape vs. portrait orientations so you'll need to redetect it when it changes. I would advise against remembering these values as the user could connect/disconnect a bluetooth keyboard at any time.
var element = document.getElementById("element"); // the input field
var focused = false;
var virtualKeyboardHeight = function () {
var sx = document.body.scrollLeft, sy = document.body.scrollTop;
var naturalHeight = window.innerHeight;
window.scrollTo(sx, document.body.scrollHeight);
var keyboardHeight = naturalHeight - window.innerHeight;
window.scrollTo(sx, sy);
return keyboardHeight;
};
element.onfocus = function () {
focused = true;
setTimeout(function() {
element.value = "keyboardHeight = " + virtualKeyboardHeight()
}, 1); // to allow for orientation scrolling
};
window.onresize = function () {
if (focused) {
element.value = "keyboardHeight = " + virtualKeyboardHeight();
}
};
element.onblur = function () {
focused = false;
};
Note that when the user is using a bluetooth keyboard, the keyboardHeight is 44 which is the height of the [previous][next] toolbar.
There is a tiny bit of flicker when you do this detection, but it doesn't seem possible to avoid it.
For this you need to update your Project Facets setting.
Project (right click) -> Properties -> Project Facets from left navigation.
If it is not open...click on the link, Check the Dynamic Web Module Check Box and select the respective version (Probably 2.4). Click on Apply Button and then Click on OK.
I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.
Main Class:-
String jsonStr = "[{\r\n" + " \"name\": \"John\",\r\n" + " \"city\": \"Berlin\",\r\n"
+ " \"cars\": [\r\n" + " \"FIAT\",\r\n" + " \"Toyata\"\r\n"
+ " ],\r\n" + " \"job\": \"Teacher\"\r\n" + " },\r\n" + " {\r\n"
+ " \"name\": \"Mark\",\r\n" + " \"city\": \"Oslo\",\r\n" + " \"cars\": [\r\n"
+ " \"VW\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n"
+ " \"job\": \"Doctor\"\r\n" + " }\r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);
for (MyPojo itr : jsonObj) {
System.out.println("Val of getName is: " + itr.getName());
System.out.println("Val of getCity is: " + itr.getCity());
System.out.println("Val of getJob is: " + itr.getJob());
System.out.println("Val of getCars is: " + itr.getCars() + "\n");
}
POJO:
public class MyPojo {
private List<String> cars = new ArrayList<String>();
private String name;
private String job;
private String city;
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} }
RESULT:-
Val of getName is: John
Val of getCity is: Berlin
Val of getJob is: Teacher
Val of getCars is: [FIAT, Toyata]
Val of getName is: Mark
Val of getCity is: Oslo
Val of getJob is: Doctor
Val of getCars is: [VW, Toyata]
I had a bug in IE7 (works fine in IE6) where using the above jQuery methods would clear the select in the DOM but not on screen. Using the IE Developer Toolbar I could confirm that the select had been cleared and had the new items, but visually the select still showed the old items - even though you could not select them.
The fix was to use standard DOM methods/properites (as the poster original had) to clear rather than jQuery - still using jQuery to add options.
$('#mySelect')[0].options.length = 0;
You need its pid... use "ps -A" to find it.
That may help those who works on Kotlin you can use extension function so create a kotlin file let's say "util.kt" and add this piece of code
fun Fragment.addChildFragment(fragment: Fragment, frameId: Int) {
val transaction = childFragmentManager.beginTransaction()
transaction.replace(frameId, fragment).commit()
}
Let's say this is the class of the child
class InputFieldPresentation: Fragment()
{
var views: View? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
views = inflater!!.inflate(R.layout.input_field_frag, container, false)
return views
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
...
}
...
}
Now you can add the children to the father fragment like this
FatherPresentation:Fragment()
{
...
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val fieldFragment= InputFieldPresentation()
addChildFragment(fieldFragment,R.id.fragmet_field)
}
...
}
where R.id.fragmet_field is the id of the layout which will contain the fragment.This lyout is inside the father fragment of course. Here is an example
father_fragment.xml:
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
...
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:id="@+id/fragmet_field"
android:orientation="vertical"
>
</LinearLayout>
...
</LinearLayout>
Have you tried rebuilding the statistics and/or the indexes on the Report_Opener table. All the recomplies of the SP won't be worth anything if the stats still show data from when the database was first inauguarated.
The initial query itself works quickly because the optimiser can see that the parameter will never be null. In the case of the SP the optimiser cannot be sure that the parameter will never be null.
After you install the ftp server with sudo apt-get install vsftpd
you will have to configure it. To enable write access you have to edit the /etc/vsftpd.conf
file and uncomment the
#write_enable=YES
line, so it should read
write_enable=YES
Save the file and restart vsftpd
with sudo service vsftpd restart
.
For other configuration options consult this documentation or man vsftpd.conf
You add a
float: left;
to the style of the 3 elements and make sure the parent container has
overflow: hidden; position: relative;
this makes sure the floats take up actual space.
<html>
<head>
<title>Website Title </title>
</head>
<body>
<div id="the-whole-thing" style="position: relative; overflow: hidden;">
<div id="leftThing" style="position: relative; width: 25%; background-color: blue; float: left;">
Left Side Menu
</div>
<div id="content" style="position: relative; width: 50%; background-color: green; float: left;">
Random Content
</div>
<div id="rightThing" style="position: relative; width: 25%; background-color: yellow; float: left;">
Right Side Menu
</div>
</div>
</body>
</html>
Also please note that the width: 100% and height: 100% need to be removed from the container, otherwise the 3rd block will wrap to a 2nd line.
There is possibility you forgot to add mapping for created Entity into hibernate.cfg.xml
, same error.
NickC is correct. It is also worth pointing out that the SDK location is set in Eclipse > Window menu > Preferences > Android. If your folders are different you can check the 8.3 format of any folder with dir foldername /x at the command prompt.
With Java 9, you are able to do the following to create an immutable List
:
List<Integer> immutableList = List.of(1, 2, 3, 4, 5);
List<Integer> mutableList = new ArrayList<>(immutableList);
To the parent div add a height say 50px. In the child span, add the line-height: 50px; Now the text in the span will be vertically center. This worked for me.
start the sql server agent, that should fix your problem
I am using SQL Server 2005 Express, and I had to enable Named Pipes connection to be able to backup from the Windows Command. My final script is this:
@echo off
set DB_NAME=Your_DB_Name
set BK_FILE=D:\DB_Backups\%DB_NAME%.bak
set DB_HOSTNAME=Your_DB_Hostname
echo.
echo.
echo Backing up %DB_NAME% to %BK_FILE%...
echo.
echo.
sqlcmd -E -S np:\\%DB_HOSTNAME%\pipe\MSSQL$SQLEXPRESS\sql\query -d master -Q "BACKUP DATABASE [%DB_NAME%] TO DISK = N'%BK_FILE%' WITH INIT , NOUNLOAD , NAME = N'%DB_NAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
echo Done!
echo.
It's working just fine here!!
The same thing happened to me. Here is what I did in order to get it successfully installed. I downloaded KB2999226 update from Microsofts website here: https://www.microsoft.com/en-us/download/details.aspx?id=49093
After installing this package, I started the installation process again. That worked for me.
I think the available libraries, tools, examples, and communities completely trumps the paradigm these days. For example, ML (or whatever) might be the ultimate all-purpose programming language but if you can't get any good libraries for what you are doing you're screwed.
For example, if you're making a video game, there are more good code examples and SDKs in C++, so you're probably better off with that. For a small web application, there are some great Python, PHP, and Ruby frameworks that'll get you off and running very quickly. Java is a great choice for larger projects because of the compile-time checking and enterprise libraries and platforms.
It used to be the case that the standard libraries for different languages were pretty small and easily replicated - C, C++, Assembler, ML, LISP, etc.. came with the basics, but tended to chicken out when it came to standardizing on things like network communications, encryption, graphics, data file formats (including XML), even basic data structures like balanced trees and hashtables were left out!
Modern languages like Python, PHP, Ruby, and Java now come with a far more decent standard library and have many good third party libraries you can easily use, thanks in great part to their adoption of namespaces to keep libraries from colliding with one another, and garbage collection to standardize the memory management schemes of the libraries.
Maybe I am missing something (lots of many-upvotes-members answers here that seem to be looking at this different to I, which would seem implausible that I am correct), but length is not the correct terminology for counting something. Length is usually used to obtain what you are getting, and not what you are wanting.
$cars.count
should give you what you seem to be looking for.
This works for me, I hope helps to someone.
var frm = $('#frm');
let formData = new FormData(frm[0]);
axios.post('your-url', formData)
.then(res => {
console.log({res});
}).catch(err => {
console.error({err});
});
To display a phone number with (###) ###-#### format, you can create a new HtmlHelper.
@Html.DisplayForPhone(item.Phone)
public static class HtmlHelperExtensions
{
public static HtmlString DisplayForPhone(this HtmlHelper helper, string phone)
{
if (phone == null)
{
return new HtmlString(string.Empty);
}
string formatted = phone;
if (phone.Length == 10)
{
formatted = $"({phone.Substring(0,3)}) {phone.Substring(3,3)}-{phone.Substring(6,4)}";
}
else if (phone.Length == 7)
{
formatted = $"{phone.Substring(0,3)}-{phone.Substring(3,4)}";
}
string s = $"<a href='tel:{phone}'>{formatted}</a>";
return new HtmlString(s);
}
}
DELETE FROM blob
WHERE fileid NOT IN
(SELECT id
FROM files
WHERE id is NOT NULL/*This line is unlikely to be needed
but using NOT IN...*/
)
Make the script executable by the user "Kev" and then remove the try it running through the command
sh kev@server1 /test/foo.sh
If you are using GNU make, $(CURDIR) is actually a built-in variable. It is the location where the Makefile resides the current working directory, which is probably where the Makefile is, but not always.
OUTPUT_PATH = /project1/bin/$(notdir $(CURDIR))
See Appendix A Quick Reference in http://www.gnu.org/software/make/manual/make.html
For scrolling to the element and element being at the top of the page
WebElement tempElement=driver.findElement(By.cssSelector("input[value='Excel']"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", tempElement);
Use RETURN QUERY
:
CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
RETURNS TABLE (txt text -- also visible as OUT parameter inside function
, cnt bigint
, ratio bigint) AS
$func$
BEGIN
RETURN QUERY
SELECT t.txt
, count(*) AS cnt -- column alias only visible inside
, (count(*) * 100) / _max_tokens -- I added brackets
FROM (
SELECT t.txt
FROM token t
WHERE t.chartype = 'ALPHABETIC'
LIMIT _max_tokens
) t
GROUP BY t.txt
ORDER BY cnt DESC; -- potential ambiguity
END
$func$ LANGUAGE plpgsql;
Call:
SELECT * FROM word_frequency(123);
Explanation:
It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE
is one way to do that. There are others. Data types of OUT
parameters have to match exactly what is returned by the query.
Choose names for OUT
parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.
But note the potential naming conflict between the OUT
parameter cnt
and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...
) Postgres uses the column alias over the OUT
parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:
ORDER BY 2 DESC
. Example:
ORDER BY count(*)
.plpgsql.variable_conflict
or use the special command #variable_conflict error | use_variable | use_column
in the function. See:
Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt
and cnt
in my examples.
Added a missing ;
and corrected a syntax error in the header. (_max_tokens int)
, not (int maxTokens)
- type after name.
While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric
(or a floating point type). See below.
This is what I think your query should actually look like (calculating a relative share per token):
CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
RETURNS TABLE (txt text
, abs_cnt bigint
, relative_share numeric) AS
$func$
BEGIN
RETURN QUERY
SELECT t.txt, t.cnt
, round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2) -- AS relative_share
FROM (
SELECT t.txt, count(*) AS cnt
FROM token t
WHERE t.chartype = 'ALPHABETIC'
GROUP BY t.txt
ORDER BY cnt DESC
LIMIT _max_tokens
) t
ORDER BY t.cnt DESC;
END
$func$ LANGUAGE plpgsql;
The expression sum(t.cnt) OVER ()
is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.
A final explicit RETURN
statement is not required (but allowed) when working with OUT
parameters or RETURNS TABLE
(which makes implicit use of OUT
parameters).
round()
with two parameters only works for numeric
types. count()
in the subquery produces a bigint
result and a sum()
over this bigint
produces a numeric
result, thus we deal with a numeric
number automatically and everything just falls into place.
Easiest way is to use System.Linq as previously described
using System.Linq;
public int GetHighestValue(List<MyTypes> list)
{
return list.Count > 0 ? list.Max(t => t.Age) : 0; //could also return -1
}
This is also possible with a Dictionary
using System.Linq;
public int GetHighestValue(Dictionary<MyTypes, OtherType> obj)
{
return obj.Count > 0 ? obj.Max(t => t.Key.Age) : 0; //could also return -1
}
The problem was that you attempted to modify the list you were referencing within the loop that used the list len()
. When you remove the item from the list, then the new len()
is calculated on the next loop.
For example, after the first run, when you removed (i)
using l.pop(i)
, that happened successfully but on the next loop the length of the list has changed so all index numbers have been shifted. To a certain point the loop attempts to run over a shorted list throwing the error.
Doing this outside the loop works, however it would be better to build and new list by first declaring and empty list before the loop, and later within the loop append everything you want to keep to the new list.
For those of you who may have come to the same problem.
I think it has changed again.
For posting this works in Xcode 8.2.
NotificationCenter.default.post(Notification(name:.UIApplicationWillResignActive)
I don't think there is a built-in command to do this, but it is safe to do the following:
git checkout master
git branch -d bug-fix-a
When you use -d
, git will refuse to delete the branch unless it is completely merged into HEAD
or its upstream remote-tracking branch. So, you could always loop over the output of git for-each-ref
and try to delete each branch. The problem with that approach is that I suspect that you probably don't want bug-fix-d
to be deleted just because origin/bug-fix-d
contains its history. Instead, you could create a script something like the following:
#!/bin/sh
git checkout master &&
for r in $(git for-each-ref refs/heads --format='%(refname:short)')
do
if [ x$(git merge-base master "$r") = x$(git rev-parse --verify "$r") ]
then
if [ "$r" != "master" ]
then
git branch -d "$r"
fi
fi
done
Warning: I haven't tested this script - use only with care...
UPDATE
The bookmarklet hack below is broken due to XHR issues and API changes.
Thankfully Github now has "A Whole New Code Search" which does the job superbly.
Checkout this voodoo: Github code search userscript.
Follow the directions there, or if you hate bloating your browser with scripts and extensions, use my bookmarkified bundle of the userscript:
javascript:(function(){var s='https://raw.githubusercontent.com/skratchdot/github-enhancement-suite/master/build/github-enhancement-suite.user.js',t='text/javascript',d=document,n=navigator,e;(e=d.createElement('script')).src=s;e.type=t;d.getElementsByTagName('head')[0].appendChild(e)})();doIt('');void('');
Save the source above as the URL of a new bookmark. Browse to any Github repo, click the bookmark, and bam: in-page, ajaxified code search.
CAVEAT Github must index a repo before you can search it.
Abracadabra...
Here's a sample search from the annotated ECMAScript 5.1 specification repository:
max-width is the width of the target display area, e.g. the browser; max-device-width is the width of the device's entire rendering area, i.e. the actual device screen.
• If you are using the max-device-width, when you change the size of the browser window on your desktop, the CSS style won't change to different media query setting;
• If you are using the max-width, when you change the size of the browser on your desktop, the CSS will change to different media query setting and you might be shown with the styling for mobiles, such as touch-friendly menus.
Use animation-delay
:
div {
width: 100px;
height: 100px;
background: red;
opacity: 0;
animation: fadeIn 3s;
animation-delay: 5s;
animation-fill-mode: forwards;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
Since the question is so popular, it may be useful to add on what to do if you want to control the type property name and its value.
The long way is to write custom JsonConverter
s to handle (de)serialization by manually checking and setting the type property.
A simpler way is to use JsonSubTypes, which handles all the boilerplate via attributes:
[JsonConverter(typeof(JsonSubtypes), "Sound")]
[JsonSubtypes.KnownSubType(typeof(Dog), "Bark")]
[JsonSubtypes.KnownSubType(typeof(Cat), "Meow")]
public class Animal
{
public virtual string Sound { get; }
public string Color { get; set; }
}
public class Dog : Animal
{
public override string Sound { get; } = "Bark";
public string Breed { get; set; }
}
public class Cat : Animal
{
public override string Sound { get; } = "Meow";
public bool Declawed { get; set; }
}
If you happen to be using date in a MacOS environment, try this:
ST1:~ ejf$ date
Mon Feb 20 21:55:48 CST 2017
ST1:~ ejf$ date -v-1m +%m
01
ST1:~ ejf$ date -v+1m +%m
03
Also, I'd rather calculate the previous and next month on the first day of each month, this way you won't have issues with months ending the 30/31 or 28/29 (Feb/Feb leap year)
use css :
p { margin:0 }
Try this wonderful plugin http://www.getfirebug.com :)
EDIT: Firebug is now closed as a project, it was migrated to https://www.mozilla.org/en-US/firefox/developer
For legend labels can use something like below. Legendlabels are the plot lines saved. modFreq are where the name of the actual labels corresponding to the plot lines. Then the third parameter is the location of the legend. Lastly, you can pass in any arguments as I've down here but mainly need the first three. Also, you are supposed to if you set the labels correctly in the plot command. To just call legend with the location parameter and it finds the labels in each of the lines. I have had better luck making my own legend as below. Seems to work in all cases where have never seemed to get the other way going properly. If you don't understand let me know:
legendLabels = []
for i in range(modSize):
legendLabels.append(ax.plot(x,hstack((array([0]),actSum[j,semi,i,semi])), color=plotColor[i%8], dashes=dashes[i%4])[0]) #linestyle=dashs[i%4]
legArgs = dict(title='AM Templates (Hz)',bbox_to_anchor=[.4,1.05],borderpad=0.1,labelspacing=0,handlelength=1.8,handletextpad=0.05,frameon=False,ncol=4, columnspacing=0.02) #ncol,numpoints,columnspacing,title,bbox_transform,prop
leg = ax.legend(tuple(legendLabels),tuple(modFreq),'upper center',**legArgs)
leg.get_title().set_fontsize(tick_size)
You can also use the leg to change fontsizes or nearly any parameter of the legend.
Global title as stated in the above comment can be done with adding text per the link provided: http://matplotlib.sourceforge.net/examples/pylab_examples/newscalarformatter_demo.html
f.text(0.5,0.975,'The new formatter, default settings',horizontalalignment='center',
verticalalignment='top')
This is a bit of self promotion, but I built a tool to do just this that you might find useful, called GeoPeeker.
It remotely accesses a site from servers spread around the world, renders the page with webkit and sends back an image. It will also report the IP address and DNS information of the site as it appears from that location.
There are no ads, and it's very stream-lined to serve this one purpose. It's still in development, and feedback is welcome. Here's hoping somebody besides myself finds it useful!
EDIT: Firefox and Google Chrome now have a built-in JSON
object, so you can just say alert(JSON.stringify(myArray))
without needing to use a jQuery plugin. This is not part of the Javascript language spec, so you shouldn't rely on the JSON
object being present in all browsers, but for debugging purposes it's incredibly useful.
I tend to use the jQuery-json plugin as follows:
alert( $.toJSON(myArray) );
This prints the array in a format like
[5, 6, 7, 11]
However, for debugging your Javascript code, I highly recommend Firebug It actually comes with a Javascript console, so you can type out Javascript code for any page and see the results. Things like arrays are already printed in the human-readable form used above.
Firebug also has a debugger, as well as screens for helping you view and debug your HTML and CSS.
Here are the steps to add a remote, fetch branches, and cherry-pick a commit
# Cloning our fork
$ git clone [email protected]:ifad/rest-client.git
# Adding (as "endel") the repo from we want to cherry-pick
$ git remote add endel git://github.com/endel/rest-client.git
# Fetch their branches
$ git fetch endel
# List their commits
$ git log endel/master
# Cherry-pick the commit we need
$ git cherry-pick 97fedac
Source: https://coderwall.com/p/sgpksw
You're looking for itertools.compress
:
>>> from itertools import compress
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> list(compress(list_a, fil))
[1, 4]
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> %timeit list(compress(list_a, fil))
100000 loops, best of 3: 2.58 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v] #winner
100000 loops, best of 3: 1.98 us per loop
>>> list_a = [1, 2, 4, 6]*100
>>> fil = [True, False, True, False]*100
>>> %timeit list(compress(list_a, fil)) #winner
10000 loops, best of 3: 24.3 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]
10000 loops, best of 3: 82 us per loop
>>> list_a = [1, 2, 4, 6]*10000
>>> fil = [True, False, True, False]*10000
>>> %timeit list(compress(list_a, fil)) #winner
1000 loops, best of 3: 1.66 ms per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]
100 loops, best of 3: 7.65 ms per loop
Don't use filter
as a variable name, it is a built-in function.
I think there are two ways to make a div center align through CSS.
.middleDiv {
position : absolute;
width : 200px;
height : 200px;
left : 50%;
top : 50%;
margin-left : -100px; /* half of the width */
margin-top : -100px; /* half of the height */
}
This is the simple and best way. for the demo please visit below link:
http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html
In Swift :- var str_url = yourUrl.absoluteString
It will result a url in string.
As of PHP 7.1 you can simply do this:
$date = new DateTime( "NOW" );
echo $date->format( "m-d-Y H:i:s.u" );
It will display as:
04-11-2018 10:54:01.321688
If you want to by pass the time and resources it takes to count(*) your 3million row tables. Try this per SQL SERVER Central by Kendal Van Dyke.
Row Counts Using sysindexes If you're using SQL 2000 you'll need to use sysindexes like so:
-- Shows all user tables and row counts for the current database
-- Remove OBJECTPROPERTY function call to include system objects
SELECT o.NAME,
i.rowcnt
FROM sysindexes AS i
INNER JOIN sysobjects AS o ON i.id = o.id
WHERE i.indid < 2 AND OBJECTPROPERTY(o.id, 'IsMSShipped') = 0
ORDER BY o.NAME
If you're using SQL 2005 or 2008 querying sysindexes will still work but Microsoft advises that sysindexes may be removed in a future version of SQL Server so as a good practice you should use the DMVs instead, like so:
-- Shows all user tables and row counts for the current database
-- Remove is_ms_shipped = 0 check to include system objects
-- i.index_id < 2 indicates clustered index (1) or hash table (0)
SELECT o.name,
ddps.row_count
FROM sys.indexes AS i
INNER JOIN sys.objects AS o ON i.OBJECT_ID = o.OBJECT_ID
INNER JOIN sys.dm_db_partition_stats AS ddps ON i.OBJECT_ID = ddps.OBJECT_ID
AND i.index_id = ddps.index_id
WHERE i.index_id < 2 AND o.is_ms_shipped = 0 ORDER BY o.NAME
Try this:
in.nextLine();
This advances the Scanner to the next line.
You can append to your PATH
in a minimal fashion. No need for
parentheses unless you're appending more than one element. It also
usually doesn't need quotes. So the simple, short way to append is:
path+=/some/new/bin/dir
This lower-case syntax is using path
as an array, yet also
affects its upper-case partner equivalent, PATH
(to which it is
"bound" via typeset
).
(Notice that no :
is needed/wanted as a separator.)
Then the common pattern for testing a new script/executable becomes:
path+=$PWD/.
# or
path+=$PWD/bin
You can sprinkle path settings around your .zshrc
(as above) and it will naturally lead to the earlier listed settings taking precedence (though you may occasionally still want to use the "prepend" form path=(/some/new/bin/dir $path)
).
Treating path
this way (as an array) also means: no need to do a
rehash
to get the newly pathed commands to be found.
Also take a look at vared path
as a dynamic way to edit path
(and other things).
You may only be interested in path
for this question, but since
we're talking about exports and arrays, note that
arrays generally cannot be exported.
You can even prevent PATH
from taking on duplicate entries
(refer to
this
and this):
typeset -U path
There are three states of button
button
button:hover
button:active
Normal:
.button
{
//your css
}
Active
.button:active
{
//your css
}
Hover
.button:hover
{
//your css
}
SNIPPET:
Use :active
to style the active state of button.
button:active{_x000D_
background-color:red;_x000D_
}
_x000D_
<button>Click Me</button>
_x000D_
use inline-block
instead of inline
. Read more information here about the difference between inline and inline-block.
.inline {
display: inline-block;
border: 1px solid red;
margin:10px;
}
I personnaly like to map esc
to the command :noh
as follow:
map <esc> :noh<cr>
I wrote a whole article recently about Vim search: how to search on vanilla Vim and the best plugin to enhance the search features.
You should really post your code(a), but here goes. Start with something like:
#include <stdio.h>
#include <dirent.h>
int main (int argc, char *argv[]) {
struct dirent *pDirent;
DIR *pDir;
// Ensure correct argument count.
if (argc != 2) {
printf ("Usage: testprog <dirname>\n");
return 1;
}
// Ensure we can open directory.
pDir = opendir (argv[1]);
if (pDir == NULL) {
printf ("Cannot open directory '%s'\n", argv[1]);
return 1;
}
// Process each entry.
while ((pDirent = readdir(pDir)) != NULL) {
printf ("[%s]\n", pDirent->d_name);
}
// Close directory and exit.
closedir (pDir);
return 0;
}
You need to check in your case that args[1]
is both set and refers to an actual directory. A sample run, with tmp
is a subdirectory off my current directory but you can use any valid directory, gives me:
testprog tmp
[.]
[..]
[file1.txt]
[file1_file1.txt]
[file2.avi]
[file2_file2.avi]
[file3.b.txt]
[file3_file3.b.txt]
Note also that you have to pass a directory in, not a file. When I execute:
testprog tmp/file1.txt
I get:
Cannot open directory 'tmp/file1.txt'
That's because it's a file rather than a directory (though, if you're sneaky, you can attempt to use diropen(dirname(argv[1]))
if the initial diropen
fails).
(a) This has now been rectified but, since this answer has been accepted, I'm going to assume it was the issue of whatever you were passing in.
you need to set @Body
in interface
@Headers({ "Content-Type: application/json;charset=UTF-8"})
@POST("Auth/Login")
Call<ApiResponse> loginWithPhone(@Body HashMap<String, String> fields);
To pass the raw body to retrofit just use:
HashMap<String,String> SendData =new HashMap<>();
SendData.put("countryCode",ccode);
SendData.put("phoneNumber",phone);
Call<ApiResponse>call = serviceInterface.loginWithPhone(SendData);
this works for me:
Seen from a non-PHP guru perspective, this should do exactly what us desired to:
<style>
[name$='pdf'] { width:100%; height: auto;}
</style>
When you type "java -version", you see three version numbers - the java version (on mine, that's "1.6.0_07
"), the Java SE Runtime Environment version ("build 1.6.0_07-b06
"), and the HotSpot version (on mine, that's "build 10.0-b23, mixed mode"
). I suspect the "11.0" you are seeing is the HotSpot version.
Update: HotSpot is (or used to be, now they seem to use it to mean the whole VM) the just-in-time compiler that is built in to the Java Virtual Machine. God only knows why Sun gives it a separate version number.
var Search= React.createClass({
getInitialState: () => { showResults: false },
onClick: () => this.setState({ showResults: true }),
render: function () {
const { showResults } = this.state;
return (
<div className="date-range">
<input type="submit" value="Search" onClick={this.handleClick} />
{showResults && <Results />}
</div>
);
}
});
var Results = React.createClass({
render: function () {
return (
<div id="results" className="search-results">
Some Results
</div>
);
}
});
React.renderComponent(<Search /> , document.body);
Note: I don't know the correct answer, but the below is just my personal speculation!
As has been mentioned a 0 before a number means it's octal:
04524 // octal, leading 0
Imagine needing to come up with a system to denote hexadecimal numbers, and note we're working in a C style environment. How about ending with h like assembly? Unfortunately you can't - it would allow you to make tokens which are valid identifiers (eg. you could name a variable the same thing) which would make for some nasty ambiguities.
8000h // hex
FF00h // oops - valid identifier! Hex or a variable or type named FF00h?
You can't lead with a character for the same reason:
xFF00 // also valid identifier
Using a hash was probably thrown out because it conflicts with the preprocessor:
#define ...
#FF00 // invalid preprocessor token?
In the end, for whatever reason, they decided to put an x after a leading 0 to denote hexadecimal. It is unambiguous since it still starts with a number character so can't be a valid identifier, and is probably based off the octal convention of a leading 0.
0xFF00 // definitely not an identifier!
Nearly verbatim from Iterate over pairs in a list (circular fashion) in Python:
def pairs(seq):
i = iter(seq)
prev = next(i)
for item in i:
yield prev, item
prev = item
JavaScript's OOP is a little funky (or a lot) and it takes some getting used to. This first thing you need to keep in mind is that there are no Classes and thinking in terms of classes can trip you up. And in order to use a method attached to a Constructor (the JavaScript equivalent of a Class definition) you need to instantiate your object. For example:
Ninja = function (name) {
this.name = name;
};
aNinja = new Ninja('foxy');
aNinja.name; //-> 'foxy'
enemyNinja = new Ninja('boggis');
enemyNinja.name; //=> 'boggis'
Note that Ninja
instances have the same properties but aNinja
cannot access the properties of enemyNinja
. (This part should be really easy/straightforward) Things get a bit different when you start adding stuff to the prototype
:
Ninja.prototype.jump = function () {
return this.name + ' jumped!';
};
Ninja.prototype.jump(); //-> Error.
aNinja.jump(); //-> 'foxy jumped!'
enemyNinja.jump(); //-> 'boggis jumped!'
Calling this directly will throw an error because this
only points to the correct object (your "Class") when the Constructor is instantiated (otherwise it points to the global object, window
in a browser)
If you need to pass data from one controller to another you must pass data by route values.Because both are different request.if you send data from one page to another then you have to user query string(same as route values).
But you can do one trick :
In your calling action call the called action as a simple method :
public class ServerController : Controller
{
[HttpPost]
public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
{
XDocument updatedResultsDocument = myService.UpdateApplicationPools();
ApplicationPoolController pool=new ApplicationPoolController(); //make an object of ApplicationPoolController class.
return pool.UpdateConfirmation(updatedResultsDocument); // call the ActionMethod you want as a simple method and pass the model as an argument.
// Redirect to ApplicationPool controller and pass
// updatedResultsDocument to be used in UpdateConfirmation action method
}
}
OO Abstraction occurs during class level design, with the objective of hiding the implementation complexity of how the the features offered by an API / design / system were implemented, in a sense simplifying the 'interface' to access the underlying implementation.
The process of abstraction can be repeated at increasingly 'higher' levels (layers) of classes, which enables large systems to be built without increasing the complexity of code and understanding at each layer.
For example, a Java developer can make use of the high level features of FileInputStream without concern for how it works (i.e. file handles, file system security checks, memory allocation and buffering will be managed internally, and are hidden from consumers). This allows the implementation of FileInputStream
to be changed, and as long as the API (interface) to FileInputStream
remains consistent, code built against previous versions will still work.
Similarly, when designing your own classes, you will want to hide internal implementation details from others as far as possible.
In the Booch definition1, OO Encapsulation is achieved through Information Hiding, and specifically around hiding internal data (fields / members representing the state) owned by a class instance, by enforcing access to the internal data in a controlled manner, and preventing direct, external change to these fields, as well as hiding any internal implementation methods of the class (e.g. by making them private).
For example, the fields of a class can be made private
by default, and only if external access to these was required, would a get()
and/or set()
(or Property
) be exposed from the class. (In modern day OO languages, fields can be marked as readonly
/ final
/ immutable
which further restricts change, even within the class).
Example where NO information hiding has been applied (Bad Practice):
class Foo {
// BAD - NOT Encapsulated - code external to the class can change this field directly
// Class Foo has no control over the range of values which could be set.
public int notEncapsulated;
}
Example where field encapsulation has been applied:
class Bar {
// Improvement - access restricted only to this class
private int encapsulatedPercentageField;
// The state of Bar (and its fields) can now be changed in a controlled manner
public void setEncapsulatedField(int percentageValue) {
if (percentageValue >= 0 && percentageValue <= 100) {
encapsulatedPercentageField = percentageValue;
}
// else throw ... out of range
}
}
Example of immutable / constructor-only initialization of a field:
class Baz {
private final int immutableField;
public void Baz(int onlyValue) {
// ... As above, can also check that onlyValue is valid
immutableField = onlyValue;
}
// Further change of `immutableField` outside of the constructor is NOT permitted, even within the same class
}
Re : Abstraction vs Abstract Class
Abstract classes are classes which promote reuse of commonality between classes, but which themselves cannot directly be instantiated with new()
- abstract classes must be subclassed, and only concrete
(non abstract) subclasses may be instantiated. Possibly one source of confusion between Abstraction
and an abstract class
was that in the early days of OO, inheritance was more heavily used to achieve code reuse (e.g. with associated abstract base classes). Nowadays, composition is generally favoured over inheritance, and there are more tools available to achieve abstraction, such as through Interfaces, events / delegates / functions, traits / mixins etc.
Re : Encapsulation vs Information Hiding
The meaning of encapsulation appears to have evolved over time, and in recent times, encapsulation
can commonly also used in a more general sense when determining which methods, fields, properties, events etc to bundle into a class.
Quoting Wikipedia:
In the more concrete setting of an object-oriented programming language, the notion is used to mean either an information hiding mechanism, a bundling mechanism, or the combination of the two.
For example, in the statement
I've encapsulated the data access code into its own class
.. the interpretation of encapsulation is roughly equivalent to the Separation of Concerns or the Single Responsibility Principal (the "S" in SOLID), and could arguably be used as a synonym for refactoring.
[1] Once you've seen Booch's encapsulation cat picture you'll never be able to forget encapsulation - p46 of Object Oriented Analysis and Design with Applications, 2nd Ed
i'd just do a simple check to see if d[a] exists and if not initialize it...
var a = "1",
b = "hello",
c = { "100" : "some important data" },
d = {};
if (d[a] === undefined) {
d[a] = {}
};
d[a]["greeting"] = b;
d[a]["data"] = c;
console.debug (d);
I also face the similar Issue. Nothing programmer has to do to resolve this error. I informed to my oracle DBA team. They kill the session and worked like a charm.
Go to your project's properties and set the start page property.
All you need to do is add \n or to write on files go \r\n.
Examples:
say you wanted to write duck(line break) cow this is how you would do it Console.WriteLine("duck\n cow");
Edit: I think I didn't understand the question. You can use
@"duck
cow".Replace("\r\n", "")
as a linebreak in code, that produces \r\n which is used Windows.
$(document).ready(function() {
//...
//clear on focus
$('.input').focus(function() {
$('.input').val("");
});
//clear when submitted
$('.button').click(function() {
$('.input').val("");
});
});
Actually in newer Osx os's, this is stored in /Library/WebServer/Documents/
The .en file is just an html file, but it needs special permissions to change, so I just made a folder for my stuff and then accessed it by
user.local/Folder/file.html
Steves answer is correct though outdated with fragments. Here is an example with FragmentDialog.
The class:
public class SomeDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setMessage("Sure you wanna do this!")
.setNegativeButton(android.R.string.no, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do nothing (will close dialog)
}
})
.setPositiveButton(android.R.string.yes, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do something
}
})
.create();
}
}
To start dialog:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Create and show the dialog.
SomeDialog newFragment = new SomeDialog ();
newFragment.show(ft, "dialog");
You could also let the class implement onClickListener
and use that instead of embedded listeners.
You can do it via ssh.
ssh [email protected] "python ./hello.py"
You can also edit the script in ssh using a textual editor or X11 forwarding.
One way is to use the lattice package and xyplot():
R> DF <- data.frame(x=1:10, y=rnorm(10)+5,
+> z=sample(letters[1:3], 10, replace=TRUE))
R> DF
x y z
1 1 3.91191 c
2 2 4.57506 a
3 3 3.16771 b
4 4 5.37539 c
5 5 4.99113 c
6 6 5.41421 a
7 7 6.68071 b
8 8 5.58991 c
9 9 5.03851 a
10 10 4.59293 b
R> with(DF, xyplot(y ~ x, group=z))
By giving explicit grouping information via variable z
, you obtain different colors. You can specify colors etc, see the lattice documentation.
Because z
here is a factor variable for which we obtain the levels (== numeric indices), you can also do
R> with(DF, plot(x, y, col=z))
but that is less transparent (to me, at least :) then xyplot()
et al.
__FUNCTION__
is non standard, __func__
exists in C99 / C++11. The others (__LINE__
and __FILE__
) are just fine.
It will always report the right file and line (and function if you choose to use __FUNCTION__
/__func__
). Optimization is a non-factor since it is a compile time macro expansion; it will never affect performance in any way.
I think there are some good reasons on this page to adopt the second method -using explicit JOINs. The clincher though is that when the JOIN criteria are removed from the WHERE clause it becomes much easier to see the remaining selection criteria in the WHERE clause.
In really complex SELECT statements it becomes much easier for a reader to understand what is going on.
execute below line:
SET FOREIGN_KEY_CHECKS = 0;
FOREIGN_KEY_CHECKS option specifies whether or not to check foreign key constraints for InnoDB tables.
-- Specify to check foreign key constraints (this is the default)
SET FOREIGN_KEY_CHECKS = 1;
-- Do not check foreign key constraints
SET FOREIGN_KEY_CHECKS = 0;
When to Use :
Temporarily disabling referential constraints (set FOREIGN_KEY_CHECKS to 0) is useful when you need to re-create the tables and load data in any parent-child order.
using Calendar is simple:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Madrid"));
Date currentDate = calendar.getTime();
I also found this to be useful when i wanted to place an icon with absolute positioning inside a link <a>
tag.
I thought about the <img>
tag first, but default styling of those tags inside links typically have border styling and/or shadow effects. Plus, it feels wrong to use an <img>
tag without defining an "src" attribute whereas i'm using a background-image style sheet declaration so that the image doesn't ghost and drag.
At this point you're thinking of tags like <span>
or <i>
- in which case <i>
makes so much sense as this type of icon.
All in all i think its benefit besides being intuitive is that it requires minimal style sheet adjustments to make this tag work as an icon.
The doxypy input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well.
I learned that
delete CKEDITOR.instances[editorName];
by itself, actually removed the instance. ALL other methods i have read and seen, including what was found here at stackoverflow from its users, did not work for me.
In my situation, im using an ajax call to pull a copy of the content wrapped around the and 's. The problem happens to be because i am using a jQuery .live event to bind a "Edit this document" link and then applying the ckeditor instance after success of the ajax load. This means, that when i click another link a link with another .live event, i must use the delete CKEDITOR.instances[editorName] as part of my task of clearing the content window (holding the form), then re-fetching content held in the database or other resource.
For myself, I would assume unsigned int is platform specific. Integer could be 8 bits, 16 bits, 32 bits or even 64 bits.
DWORD in the other hand, specifies its own size, which is Double Word. Word are 16 bits so DWORD will be known as 32 bit across all platform
Using $index
works perfectly well in basic cases, and @charlietfl's answer is great. But sometimes, $index
isn't enough.
Imagine you have a single array, which you're presenting in two different ng-repeat's. One of those ng-repeat's is filtered for objects that have a truthy property, and the other is filtered for a falsy property. Two different filtered arrays are being presented, which derive from a single original array. (Or, if it helps to visualize: perhaps you have a single array of people, and you want one ng-repeat for the women in that array, and another for the men in that same array.) Your goal: delete reliably from the original array, using information from the members of the filtered arrays.
In each of those filtered arrays, $index won't be the index of the item within the original array. It'll be the index in the filtered sub-array. So, you won't be able to tell the person's index in the original people
array, you'll only know the $index from the women
or men
sub-array. Try to delete using that, and you'll have items disappearing from everywhere except where you wanted. What to do?
If you're lucky enough be using a data model includes a unique identifier for each object, then use that instead of $index, to find the object and splice
it out of the main array. (Use my example below, but with that unique identifier.) But if you're not so lucky?
Angular actually augments each item in an ng-repeated array (in the main, original array) with a unique property called $$hashKey
. You can search the original array for a match on the $$hashKey
of the item you want to delete, and get rid of it that way.
Note that $$hashKey
is an implementation detail, not included in the published API for ng-repeat. They could remove support for that property at any time. But probably not. :-)
$scope.deleteFilteredItem = function(hashKey, sourceArray){
angular.forEach(sourceArray, function(obj, index){
// sourceArray is a reference to the original array passed to ng-repeat,
// rather than the filtered version.
// 1. compare the target object's hashKey to the current member of the iterable:
if (obj.$$hashKey === hashKey) {
// remove the matching item from the array
sourceArray.splice(index, 1);
// and exit the loop right away
return;
};
});
}
Invoke with:
ng-click="deleteFilteredItem(item.$$hashKey, refToSourceArray)"
EDIT: Using a function like this, which keys on the $$hashKey
instead of a model-specific property name, also has the significant added advantage of making this function reusable across different models and contexts. Provide it with your array reference, and your item reference, and it should just work.
ArrayDeque
is probably the fastest object-based queue in the JDK; Trove has the TIntQueue
interface, but I don't know where its implementations live.
<script type="text/javascript">
$(window).ready(function () {
alert("Window Loaded");
});
</script>
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
If you want to replace a "full nested dictionary with arrays" you can use this snippet :
It will replace any "old_value" by "new_value". It's roughly doing a depth-first rebuilding of the dictionary. It can even work with List or Str/int given as input parameter of first level.
def update_values_dict(original_dict, future_dict, old_value, new_value):
# Recursively updates values of a nested dict by performing recursive calls
if isinstance(original_dict, Dict):
# It's a dict
tmp_dict = {}
for key, value in original_dict.items():
tmp_dict[key] = update_values_dict(value, future_dict, old_value, new_value)
return tmp_dict
elif isinstance(original_dict, List):
# It's a List
tmp_list = []
for i in original_dict:
tmp_list.append(update_values_dict(i, future_dict, old_value, new_value))
return tmp_list
else:
# It's not a dict, maybe a int, a string, etc.
return original_dict if original_dict != old_value else new_value
SELECT CLASS,
isnull([AZ],0),
isnull([CA],0),
isnull([TX],0)
FROM #TEMP
PIVOT (SUM(DATA)
FOR STATE IN ([AZ], [CA], [TX])) AS PVT
ORDER BY CLASS
Use <br/>
. For example:
Change log, upgrade version
Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`
Just use floatval()
.
E.g.:
$var = '122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
And in case you wonder doubleval()
is just an alias for floatval()
.
And as the other say, in a financial application, float values are critical as these are not precise enough. E.g. adding two floats could result in something like 12.30000000001
and this error could propagate.
As a general point when using a search engine to search for SQL codes make sure you put the sqlcode e.g. -302 in quote marks - like "-302" otherwise the search engine will exclude all search results including the text 302, since the - sign is used to exclude results.
I'm going to attempt to explain this without making any mistakes, but I'm betting this will attract a clarification or two in the comments.
A data frame is a list. When you subset a data frame using the name of a column and [
, what you're getting is a sublist (or a sub data frame). If you want the actual atomic column, you could use [[
, or somewhat confusingly (to me) you could do aframe[,2]
which returns a vector, not a sublist.
So try running this sequence and maybe things will be clearer:
avector <- as.vector(aframe['a2'])
class(avector)
avector <- aframe[['a2']]
class(avector)
avector <- aframe[,2]
class(avector)
I can't get that constructor to work either. This however seems to work:
# $temp = Get-ResourceFiles
$resourceFiles = New-Object System.Collections.ArrayList($null)
$resourceFiles.AddRange($temp)
You can also pass an integer in the constructor to set an initial capacity.
What do you mean when you say you want to enumerate the files? Why can't you just filter the wanted values into a fresh array?
Edit:
It seems that you can use the array constructor like this:
$resourceFiles = New-Object System.Collections.ArrayList(,$someArray)
Note the comma. I believe what is happening is that when you call a .NET method, you always pass parameters as an array. PowerShell unpacks that array and passes it to the method as separate parameters. In this case, we don't want PowerShell to unpack the array; we want to pass the array as a single unit. Now, the comma operator creates arrays. So PowerShell unpacks the array, then we create the array again with the comma operator. I think that is what is going on.
I wanted to combine a couple of posts to make a full answer of this since it does appear to be a few steps.
/etc/mysql/my.cnf
or /etc/mysql/mysql.conf.d/mysqld.cnf
[mysql]
default-character-set=utf8mb4
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0
[mysqld]
##
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci
init_connect='SET NAMES utf8mb4'
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
Again from advice above all jdbc connections had characterEncoding=UTF-8
and characterSetResults=UTF-8
removed from them
With this set -Dfile.encoding=UTF-8
appeared to make no difference.
I could still not write international text into db getting same failure as above
Now using this how-to-convert-an-entire-mysql-database-characterset-and-collation-to-utf-8
Update all your db to use utf8mb4
ALTER DATABASE YOURDB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Run this query that gives you what needs to be rung
SELECT CONCAT(
'ALTER TABLE ', table_name, ' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; ',
'ALTER TABLE ', table_name, ' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; ')
FROM information_schema.TABLES AS T, information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` AS C
WHERE C.collation_name = T.table_collation
AND T.table_schema = 'YOURDB'
AND
(C.CHARACTER_SET_NAME != 'utf8mb4'
OR
C.COLLATION_NAME not like 'utf8mb4%')
Copy paste output in editor replace all | with nothing post back into mysql when connected to correct db.
That is all that had to be done and all seems to work for me. Not the -Dfile.encoding=UTF-8
is not enabled and it appears to work as expected
E2A Still having an issue ? I certainly am in production so it turns out you do need to check over what has been done by above, since it sometimes does not work, here is reason and fix in this scenario:
show create table user
`password` varchar(255) CHARACTER SET latin1 NOT NULL,
`username` varchar(255) CHARACTER SET latin1 NOT NULL,
You can see some are still latin attempting to manually update the record:
ALTER TABLE user CONVERT TO CHARACTER SET utf8mb4;
ERROR 1071 (42000): Specified key was too long; max key length is 767 bytes
So let's narrow it down:
mysql> ALTER TABLE user change username username varchar(255) CHARACTER SET utf8mb4 not NULL;
ERROR 1071 (42000): Specified key was too long; max key length is 767 bytes
mysql> ALTER TABLE user change username username varchar(100) CHARACTER SET utf8mb4 not NULL;
Query OK, 5 rows affected (0.01 sec)
In short I had to reduce the size of that field in order to get the update to work.
Now when I run:
mysql> ALTER TABLE user CONVERT TO CHARACTER SET utf8mb4;
Query OK, 5 rows affected (0.01 sec)
Records: 5 Duplicates: 0 Warnings: 0
It all works
In case one wants to create FK constraints from UAT environment table to Live, fire below dynamic query.....
SELECT 'ALTER TABLE '||OBJ.NAME||' ADD CONSTRAINT '||CONST.NAME||' FOREIGN KEY ('||COALESCE(ACOL.NAME, COL.NAME)||') REFERENCES '
||ROBJ.NAME ||' ('||COALESCE(RACOL.NAME, RCOL.NAME) ||');'
FROM SYS.CON$ CONST
INNER JOIN SYS.CDEF$ CDEF ON CDEF.CON# = CONST.CON#
INNER JOIN SYS.CCOL$ CCOL ON CCOL.CON# = CONST.CON#
INNER JOIN SYS.COL$ COL ON (CCOL.OBJ# = COL.OBJ#) AND (CCOL.INTCOL# = COL.INTCOL#)
INNER JOIN SYS.OBJ$ OBJ ON CCOL.OBJ# = OBJ.OBJ#
LEFT JOIN SYS.ATTRCOL$ ACOL ON (CCOL.OBJ# = ACOL.OBJ#) AND (CCOL.INTCOL# = ACOL.INTCOL#)
INNER JOIN SYS.CON$ RCONST ON RCONST.CON# = CDEF.RCON#
INNER JOIN SYS.CCOL$ RCCOL ON RCCOL.CON# = RCONST.CON#
INNER JOIN SYS.COL$ RCOL ON (RCCOL.OBJ# = RCOL.OBJ#) AND (RCCOL.INTCOL# = RCOL.INTCOL#)
INNER JOIN SYS.OBJ$ ROBJ ON RCCOL.OBJ# = ROBJ.OBJ#
LEFT JOIN SYS.ATTRCOL$ RACOL ON (RCCOL.OBJ# = RACOL.OBJ#) AND (RCCOL.INTCOL# = RACOL.INTCOL#)
WHERE CONST.OWNER# = userenv('SCHEMAID')
AND RCONST.OWNER# = userenv('SCHEMAID')
AND CDEF.TYPE# = 4
AND OBJ.NAME = <table_name>;
If you don't need a signed integer, this is an alternative that uses a slightly different approach, is easy to read and doesn't require an import:
def distance(a, b):
if a > 0 and b > 0:
return max(a, b) - min(a, b)
elif a < 0 and b < 0:
return abs(a - b)
elif a == b:
return 0
return abs(a - 0) + abs(b - 0)
That's because parent.children
is a NodeList, and it doesn't support the .forEach
method (as NodeList is an array like structure but not an array), so try to call it by first converting it to array using
var children = [].slice.call(parent.children);
children.forEach(yourFunc);
I had to struggle for a little bit but I found a solution, I added
-Dsonar.coverage.exclusions=**/*.*
and the coverage metric was cancelled from the dashboard at all, so I realized that the problem was the path I was passing, not the property. In my case the path to exclude was java/org/acme/exceptions, so I used :
`-Dsonar.coverage.exclusions=**/exceptions/**/*.*`
and it worked, but since I don't have sub-folders it also works with
-Dsonar.coverage.exclusions=**/exceptions/*.*
I figured it out.
<?php $author_id=$post->post_author; ?>
<img src="<?php the_author_meta( 'avatar' , $author_id ); ?> " width="140" height="140" class="avatar" alt="<?php echo the_author_meta( 'display_name' , $author_id ); ?>" />
<?php the_author_meta( 'user_nicename' , $author_id ); ?>
For Oracle, please use this simple command:
ALTER SESSION SET current_schema = your-schema-without-quotes;
You can use multiselect
function for this.
CriteriaBuilder cb=session.getCriteriaBuilder();
CriteriaQuery<Object[]> cquery=cb.createQuery(Object[].class);
Root<Car> root=cquery.from(User.class);
cquery.multiselect(root.get("id"),root.get("Name"));
Query<Object[]> q=session.createQuery(cquery);
List<Object[]> list=q.getResultList();
System.out.println("id Name");
for (Object[] objects : list) {
System.out.println(objects[0]+" "+objects[1]);
}
This is supported by hibernate 5. createCriteria
is deprecated in further version of hibernate. So you can use criteria builder
instead.
If you use PM2 via node modules instead of globally, you'll need to set interpreter: 'none'
in order for the above solutions to work. Related docs here.
In ecosystem.config.js
:
apps: [
{
name: 'myApp',
script: 'yarn',
args: 'start',
interpreter: 'none',
},
],
If you are using laragon open the php.ini
In the interface of laragon menu-> php-> php.ini
when you open the file look for ; extension_dir = "./"
create another one without **; ** with the path of your php version to the folder ** ext ** for example
extension_dir = "C: \ laragon \ bin \ php \ php-7.3.11-Win32-VC15-x64 \ ext"
change it save it
<Directory /uploads>
Options +Indexes
</Directory>
This method creates a function that calls for the index of nth occurrences stored in an array
function nthIndexOf(search, n) {
var myArray = [];
for(var i = 0; i < myString.length; i++) { //loop thru string to check for occurrences
if(myStr.slice(i, i + search.length) === search) { //if match found...
myArray.push(i); //store index of each occurrence
}
}
return myArray[n - 1]; //first occurrence stored in index 0
}
You can use iText for do such things
//iText imports
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
for example:
try {
PdfReader reader = new PdfReader(INPUTFILE);
int n = reader.getNumberOfPages();
String str=PdfTextExtractor.getTextFromPage(reader, 2); //Extracting the content from a particular page.
System.out.println(str);
reader.close();
} catch (Exception e) {
System.out.println(e);
}
another one
try {
PdfReader reader = new PdfReader("c:/temp/test.pdf");
System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
String page = PdfTextExtractor.getTextFromPage(reader, 2);
System.out.println("Page Content:\n\n"+page+"\n\n");
System.out.println("Is this document tampered: "+reader.isTampered());
System.out.println("Is this document encrypted: "+reader.isEncrypted());
} catch (IOException e) {
e.printStackTrace();
}
the above examples can only extract the text, but you need to do some more to remove hyperlinks, bullets, heading & numbers.
For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.
it is control + p in Mac os in python 3.4 IDEL
You could also write it a little more cleaner using updateOne & $set, plus async/await.
const updateUser = async (newUser) => {
try {
await User.updateOne({ username: oldUsername }, {
$set: {
username: newUser.username,
password: newUser.password,
rights: newUser.rights
}
})
} catch (err) {
console.log(err)
}
}
Since you don't need the resulting document, you can just use updateOne instead of findOneAndUpdate.
Here's a good discussion about the difference: MongoDB 3.2 - Use cases for updateOne over findOneAndUpdate
You can either have the newly inserted ID being output to the SSMS console like this:
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar()
(instead of .ExecuteNonQuery()
) to read the resulting ID
back.
Or if you need to capture the newly inserted ID
inside T-SQL (e.g. for later further processing), you need to create a table variable:
DECLARE @OutputTbl TABLE (ID INT)
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
This way, you can put multiple values into @OutputTbl
and do further processing on those. You could also use a "regular" temporary table (#temp
) or even a "real" persistent table as your "output target" here.
This code 100% remove duplicate values from an array[as I used a[i]].....You can convert it in any OO language..... :)
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(a[i] == a[j])
{
for(int k=j;k<size;k++)
{
a[k]=a[k+1];
}
j--;
size--;
}
}
}
Use sender ID & API Key generated here: http://developers.google.com instead (browse for Google Cloud Messaging first and follow the instruction).
Given your factorGenerator
function, here is a divisorGen
that should work:
def divisorGen(n):
factors = list(factorGenerator(n))
nfactors = len(factors)
f = [0] * nfactors
while True:
yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)
i = 0
while True:
f[i] += 1
if f[i] <= factors[i][1]:
break
f[i] = 0
i += 1
if i >= nfactors:
return
The overall efficiency of this algorithm will depend entirely on the efficiency of the factorGenerator
.
For those scripting tmux, there is a command called rename-window
so e.g.
tmux rename-window -t <window> <newname>
You could use a combination of both methods eg.
.crop {_x000D_
width: 200px;_x000D_
height: 150px;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.crop img {_x000D_
width: 400px;_x000D_
height: 300px;_x000D_
margin: -75px 0 0 -100px;_x000D_
}
_x000D_
<div class="crop">_x000D_
<img src="https://i.stack.imgur.com/wPh0S.jpg" alt="Donald Duck">_x000D_
</div>
_x000D_
You can use negative margin
to move the image around within the <div/>
.
T[]
int
constant or int
expression, see n
below)T[]
has one read-only field: length
and an index operator [int]
for reading/writing data at certain indices.1.
String[] array= new String[]{};
what is the use of { } here ?
It initializes the array with the values between { }
. In this case 0 elements, so array.length == 0
and array[0] throws IndexOutOfBoundsException: 0
.
2. what is the diff between
String array=new String[];
andString array=new String[]{};
The first won't compile for two reasons while the second won't compile for one reason. The common reason is that the type of the variable array has to be an array type: String[]
not just String
. Ignoring that (probably just a typo) the difference is:
new String[] // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0] // size is known, it has 0 elements, explicitly sized
3. when am writing
String array=new String[10]{};
got error why ?
(Again, ignoring the missing []
before array
) In this case you're over-eager to tell Java what to do and you're giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {}
.
Just make up your mind and use one of those - Java thinks.
help me i am confused
String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2
(Here, "same as" means it will construct the same array.)
I use a solution that is similar to that of David above, but with an additional twist if some rows should be excluded from the count. This assumes that [UserAccountKey] is never null.
-- subtract an extra 1 if null was ranked within the partition,
-- which only happens if there were rows where [Include] <> 'Y'
dense_rank() over (
partition by [Mth]
order by case when [Include] = 'Y' then [UserAccountKey] else null end asc
)
+ dense_rank() over (
partition by [Mth]
order by case when [Include] = 'Y' then [UserAccountKey] else null end desc
)
- max(case when [Include] = 'Y' then 0 else 1 end) over (partition by [Mth])
- 1
You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
mysql $link
generally means, the resource object of the established mysqli connection to query the database.
So there are two ways of solving this problem
mysqli_query();
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));
Or, Using mysql_query()
(This is now obselete)
$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());
As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .
just use This
public ActionResult LoadCountries()
{
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select", Value = "0" });
li.Add(new SelectListItem { Text = "India", Value = "1" });
li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
li.Add(new SelectListItem { Text = "China", Value = "3" });
li.Add(new SelectListItem { Text = "Austrila", Value = "4" });
li.Add(new SelectListItem { Text = "USA", Value = "5" });
li.Add(new SelectListItem { Text = "UK", Value = "6" });
ViewData["country"] = li;
return View();
}
and in View use following.
@Html.DropDownList("Country", ViewData["country"] as List<SelectListItem>)
if you want to get data from Dataset and populate these data in a list box then use following code.
List<SelectListItem> li= new List<SelectListItem>();
for (int rows = 0; rows <= ds.Tables[0].Rows.Count - 1; rows++)
{
li.Add(new SelectListItem { Text = ds.Tables[0].Rows[rows][1].ToString(), Value = ds.Tables[0].Rows[rows][0].ToString() });
}
ViewData["FeedBack"] = li;
return View();
and in view write following code.
@Html.DropDownList("FeedBack", ViewData["FeedBack"] as List<SelectListItem>)
I always compare an MD5 hash of the modulus using these commands:
Certificate: openssl x509 -noout -modulus -in server.crt | openssl md5
Private Key: openssl rsa -noout -modulus -in server.key | openssl md5
CSR: openssl req -noout -modulus -in server.csr | openssl md5
If the hashes match, then those two files go together.
You could just use a HashSet<String>
to maintain a collection of unique objects. If the Integer
values in your map are important, then you can instead use the containsKey
method of maps to test whether your key is already in the map.
Thought of writing this answer as nothing worked from above & you don't want to specify proxy location.
If you're using httpClient
then consider this.
HttpClientHandler handler = new HttpClientHandler();
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
handler.Proxy = proxy;
var client = new HttpClient(handler);
// your next steps...
And if you're using HttpWebRequest
:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + _endpoint);
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
request.Proxy = proxy;
Kind referencce: https://medium.com/@siriphonnot/the-remote-server-returned-an-error-407-proxy-authentication-required-86ae489e401b
Use map
if the function returns the object you need or flatMap
if the function returns an Optional
. For example:
public static void main(String[] args) {
Optional<String> s = Optional.of("input");
System.out.println(s.map(Test::getOutput));
System.out.println(s.flatMap(Test::getOutputOpt));
}
static String getOutput(String input) {
return input == null ? null : "output for " + input;
}
static Optional<String> getOutputOpt(String input) {
return input == null ? Optional.empty() : Optional.of("output for " + input);
}
Both print statements print the same thing.
If you want the position relative to the document then:
$("#myTable").offset().top;
but often you will want the position relative to the closest positioned parent:
$("#myTable").position().top;
The hex values are on the mainpage of http://glyphicons.com/ in the tooltips of the specific icon.
You can use php in the style sheet. Just remember to set header("Content-type: text/css") in the style.php (or whatever then name is) file
T-SQL doesn't support arrays that I'm aware of.
What's your table structure? You could probably design a query that does this instead:
select
month,
sum(sales)
from sales_table
group by month
order by month
If you use Bootstrap, you can simply add the text-capitalize
helper class:
<p class="text-capitalize">CapiTaliZed text.</p>
EDIT: just in case the link dies again:
Text Transform
Transform text in components with text capitalization classes.
lowercased text.
UPPERCASED TEXT.
CapiTaliZed Text.<p class="text-lowercase">Lowercased text.</p> <p class="text-uppercase">Uppercased text.</p> <p class="text-capitalize">CapiTaliZed text.</p>
Note how text-capitalize only changes the first letter of each word, leaving the case of any other letters unaffected.
If we are directly use data from csv it will give combine data based on comma separation value as it is .csv file.
user1 = pd.read_csv('dataset/1.csv')
If you want to add column names using pandas, you have to do something like this. But below code will not show separate header for your columns.
col_names=['TIME', 'X', 'Y', 'Z']
user1 = pd.read_csv('dataset/1.csv', names=col_names)
To solve above problem we have to add extra filled which is supported by pandas, It is header=None
user1 = pd.read_csv('dataset/1.csv', names=col_names, header=None)
Do not hold me to this but I am pretty sure it depends on the application it self. I know many always open on the main monitor, some will reopen to the same monitor they were previously run in, and some you can set. I know for example I have shortcuts to open command windows to particular directories, and each has an option in their properties to the location to open the window in. While Outlook just remembers and opens in the last screen it was open in. Then other apps open in what ever window the current focus is in.
So I am not sure there is a way to tell every program where to open. Hope that helps some.
I use eUML2 plugin from Soyatec, under Eclipse and it works fine for the generation of UML giving the source code. This tool is useful up to Eclipse 4.4.x
mysqli_error()
As in:
$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);
Trigger error is better than die because you can use it for development AND production, it's the permanent solution.
System.currentTimeMillis()
is obviously the most efficient since it does not even create an object, but new Date()
is really just a thin wrapper about a long, so it is not far behind. Calendar
, on the other hand, is relatively slow and very complex, since it has to deal with the considerably complexity and all the oddities that are inherent to dates and times (leap years, daylight savings, timezones, etc.).
It's generally a good idea to deal only with long timestamps or Date
objects within your application, and only use Calendar
when you actually need to perform date/time calculations, or to format dates for displaying them to the user. If you have to do a lot of this, using Joda Time is probably a good idea, for the cleaner interface and better performance.
Instead of resetting it as proposed by DeathRs:
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();
we can just reset the MediaPlayer to it's begin using:
if (mp.isPlaying()) {
mp.seekTo(0)
}
Just add them in one line command 2>> error 1>> output
However, note that >>
is for appending if the file already has data. Whereas, >
will overwrite any existing data in the file.
So, command 2> error 1> output
if you do not want to append.
Just for completion's sake, you can write 1>
as just >
since the default file descriptor is the output. so 1>
and >
is the same thing.
So, command 2> error 1> output
becomes, command 2> error > output
Just modifying the above mentioned answer.
func setGradientBackground() {
let colorTop = UIColor(red: 255.0/255.0, green: 149.0/255.0, blue: 0.0/255.0, alpha: 1.0).cgColor
let colorBottom = UIColor(red: 255.0/255.0, green: 94.0/255.0, blue: 58.0/255.0, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorTop, colorBottom]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.frame = self.view.bounds
self.view.layer.insertSublayer(gradientLayer, at:0)
}
Then call this method within viewWillAppear
override func viewWillAppear(_ animated: Bool) {
setGradientBackground()
super.viewWillAppear(animated)
}
You should change the name of the remote repository to something else.
git remote add origin [email protected]:myname/oldrep.git
to
git remote add neworigin [email protected]:myname/oldrep.git
I think this should work.
Yes, these are for repository init and adding a new remote. Just with a change of name.
You've correctly diagnosed your problem, so good job. Once you call into your search code, the for loop just keeps right on going.
I'm a big fan of https://github.com/caolan/async, and it serves me well. Basically with it you'd end up with something like:
var async = require('async')
async.eachSeries(Object.keys(config), function (key, next){
search(config[key].query, function(err, result) { // <----- I added an err here
if (err) return next(err) // <---- don't keep going if there was an error
var json = JSON.stringify({
"result": result
});
results[key] = {
"result": result
}
next() /* <---- critical piece. This is how the forEach knows to continue to
the next loop. Must be called inside search's callback so that
it doesn't loop prematurely.*/
})
}, function(err) {
console.log('iterating done');
});
I hope that helps!
What works for me, let's say you have branch1 and you wanna merge it into branch2.
You open git command line go to root folder of branch2 and type:
git checkout branch1
git pull branch1
git checkout branch2
git merge branch1
git push
If you have comflicts you don't need to do git push, but first solve the conflits and then push.
Modern Spring 5+ answer using WebClient
instead of RestTemplate
.
Configure WebClient
for a specific web-service or resource as a bean (additional properties can be configured).
@Bean
public WebClient localApiClient() {
return WebClient.create("http://localhost:8080/api/v3");
}
Inject and use the bean from your service(s).
@Service
public class UserService {
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(3);
private final WebClient localApiClient;
@Autowired
public UserService(WebClient localApiClient) {
this.localApiClient = localApiClient;
}
public User getUser(long id) {
return localApiClient
.get()
.uri("/users/" + id)
.retrieve()
.bodyToMono(User.class)
.block(REQUEST_TIMEOUT);
}
}
Found a possible workaround that I don't believe was mentioned.
Here is a good description of the problem: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Basically as long as you use forms/url-encoded/plain text content types you are fine.
$.ajax({
type: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'text/plain'
},
dataType: "json",
url: "http://localhost/endpoint",
data: JSON.stringify({'DataToPost': 123}),
success: function (data) {
alert(JSON.stringify(data));
}
});
I use it with ASP.NET WebAPI2. So on the other end:
public static void RegisterWebApi(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}
This way Json formatter gets used when parsing plain text content type.
And don't forget in Web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol>
Hope this helps.
You have to indent the docstring after the function definition there (line 3, 4):
def print_lol(the_list):
"""this doesn't works"""
print 'Ain't happening'
Indented:
def print_lol(the_list):
"""this works!"""
print 'Aaaand it's happening'
Or you can use #
to comment instead:
def print_lol(the_list):
#this works, too!
print 'Hohoho'
Also, you can see PEP 257 about docstrings.
Hope this helps!
@ is used as a prefix denoting stored procedure and function parameter names, and also variable names
You can put them into a list and then sort them using their natural ordering, like so:
final List<Integer> list = Arrays.asList(11367, 11358, 11421, 11530, 11491, 11218, 11789);
Collections.sort( list );
// Use the sorted list
If the numbers are stored in the same variable, then you'll have to somehow put them into a List
and then call sort
, like so:
final List<Integer> list = new ArrayList<Integer>();
list.add( myVariable );
// Change myVariable to another number...
list.add( myVariable );
// etc...
Collections.sort( list );
// Use the sorted list
I composed this for my own use-case (es5 environment), thought this might be useful for someone, so here it is:
function deepCompare(obj1, obj2) {
var diffObj = Array.isArray(obj2) ? [] : {}
Object.getOwnPropertyNames(obj2).forEach(function(prop) {
if (typeof obj2[prop] === 'object') {
diffObj[prop] = deepCompare(obj1[prop], obj2[prop])
// if it's an array with only length property => empty array => delete
// or if it's an object with no own properties => delete
if (Array.isArray(diffObj[prop]) && Object.getOwnPropertyNames(diffObj[prop]).length === 1 || Object.getOwnPropertyNames(diffObj[prop]).length === 0) {
delete diffObj[prop]
}
} else if(obj1[prop] !== obj2[prop]) {
diffObj[prop] = obj2[prop]
}
});
return diffObj
}
This might be not really efficient, but will output an object with only different props based on second Obj.
I found that android:textColor="@android:color/secondary_text_dark"
provides a closer result to the default TextView color than android:textColor="@android:color/tab_indicator_text"
.
I suppose you have to switch between secondary_text_dark/light depending on the Theme you are using
Something like that:
var dictionary = {"data":[{"id":"0","name":"ABC"},{"id":"1", "name":"DEF"}], "images": [{"id":"0","name":"PQR"},{"id":"1","name":"xyz"}]};
for (item in dictionary) {
for (subItem in dictionary[item]) {
console.log(dictionary[item][subItem].id);
console.log(dictionary[item][subItem].name);
}
}
Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.
<?php
function getSSLPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>
When you set the SSL Version with curl to v3 then it works.
Edit:
Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.
http://curl.haxx.se/docs/caextract.html
here you can download the root certificates.
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
Then you can use the CURLOPT_SSL_VERIFYPEER
option with true
otherwise you get an error.
It indicates that you do not have a newline (usually '\n'
, aka CR or CRLF) at the end of file.
That is, simply speaking, the last byte (or bytes if you're on Windows) in the file is not a newline.
The message is displayed because otherwise there is no way to tell the difference between a file where there is a newline at the end and one where is not. Diff has to output a newline anyway, or the result would be harder to read or process automatically.
Note that it is a good style to always put the newline as a last character if it is allowed by the file format. Furthermore, for example, for C and C++ header files it is required by the language standard.
I tried all the options here but they didnt work for me. Eventually I got it working using
{{ site.url }}
Hope this helps someone who is still struggling.
yyyy-mm-dd :
/^((((19|[2-9]\d)\d{2})\-(0[13578]|1[02])\-(0[1-9]|[12]\d|3[01]))|(((19|[2-9]\d)\d{2})\-(0[13456789]|1[012])\-(0[1-9]|[12]\d|30))|(((19|[2-9]\d)\d{2})\-02\-(0[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))\-02\-29))$/g
yyyy/mm/dd :
/^((((19|[2-9]\d)\d{2})\/(0[13578]|1[02])\/(0[1-9]|[12]\d|3[01]))|(((19|[2-9]\d)\d{2})\/(0[13456789]|1[012])\/(0[1-9]|[12]\d|30))|(((19|[2-9]\d)\d{2})\/02\/(0[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))\/02\/29))$/g
mm-dd-yyyy :
/^(((0[13578]|1[02])\-(0[1-9]|[12]\d|3[01])\-((19|[2-9]\d)\d{2}))|((0[13456789]|1[012])\-(0[1-9]|[12]\d|30)\-((19|[2-9]\d)\d{2}))|(02\-(0[1-9]|1\d|2[0-8])\-((19|[2-9]\d)\d{2}))|(02\-29\-((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g
mm/dd/yyyy :
/^(((0[13578]|1[02])\/(0[1-9]|[12]\d|3[01])\/((19|[2-9]\d)\d{2}))|((0[13456789]|1[012])\/(0[1-9]|[12]\d|30)\/((19|[2-9]\d)\d{2}))|(02\/(0[1-9]|1\d|2[0-8])\/((19|[2-9]\d)\d{2}))|(02\/29\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g
dd/mm/yyyy :
/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g
dd-mm-yyyy :
/^(((0[1-9]|[12]\d|3[01])\-(0[13578]|1[02])\-((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\-(0[13456789]|1[012])\-((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\-02\-((19|[2-9]\d)\d{2}))|(29\-02\-((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g
Template argument deduction for class templates
[*this]{ std::cout << could << " be " << useful << '\n'; }
[[fallthrough]]
, [[nodiscard]]
, [[maybe_unused]]
attributes
using
in attributes to avoid having to repeat an attribute namespace.
Compilers are now required to ignore non-standard attributes they don't recognize.
Simple static_assert(expression);
with no string
no throw
unless throw()
, and throw()
is noexcept(true)
.
std::tie
with auto
const auto [it, inserted] = map.insert( {"foo", bar} );
it
and inserted
with deduced type from the pair
that map::insert
returns.std::array
s and relatively flat structsif (init; condition)
and switch (init; condition)
if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
if(decl)
to cases where decl
isn't convertible-to-bool sensibly.Generalizing range-based for loops
Fixed order-of-evaluation for (some) expressions with some modifications
.then
on future work.Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
std::string
like reference-to-character-array or substringstring const&
again. Also can make parsing a bajillion times faster."hello world"sv
char_traits
std::byte
off more than they could chew.
std::invoke
std::apply
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
result_of
is_invocable<Foo(Args...), R>
is "can you call Foo
with Args...
and get something compatible with R
", where R=void
is default.invoke_result<Foo, Args...>
is std::result_of_t<Foo(Args...)>
but apparently less confusing?[class.directory_iterator]
and [class.recursive_directory_iterator]
fstream
s can be opened with path
s, as well as with const path::value_type*
strings.
for_each_n
reduce
transform_reduce
exclusive_scan
inclusive_scan
transform_exclusive_scan
transform_inclusive_scan
Added for threading purposes, exposed even if you aren't using them threaded
atomic<T>
::is_always_lockfree
std::lock
pain when locking more than one mutex at a time.std
algorithms, and related machinery[func.searchers]
and [alg.search]
std::function
for allocatorsstd::sample
, sampling from a range?
try_emplace
and insert_or_assign
Splicing for map<>
, unordered_map<>
, set<>
, and unordered_set<>
non-const .data()
for string.
non-member std::size
, std::empty
, std::data
std::begin
/end
The emplace
family of functions now returns a reference to the created object.
unique_ptr<T[]>
fixes and other unique_ptr
tweaks.weak_from_this
and some fixed to shared from thisstd
datatype improvements:{}
construction of std::tuple
and other improvementsC++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
std
implementations exposedstd::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughlygcd
and lcm
std::uncaught_exceptions
std::as_const
std::bool_constant
_v
template variablesstd::void_t<T>
std::owner_less<void>
std::less<void>
, but for smart pointers to sort based on contentsstd::chrono
polishstd::conjunction
, std::disjunction
, std::negation
exposedstd::not_fn
std
std::less
.<codecvt>
memory_order_consume
result_of
, replaced with invoke_result
shared_ptr::unique
, it isn't very threadsafeIsocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
register
, keyword reserved for future usebool b; ++b;
<functional>
stuff, random_shuffle
std::function
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
https://isocpp.org/files/papers/p0636r0.html
Try and retrieve the text property of the link button in the code behind:
protected void ENameLinkBtn_Click (object sender, EventArgs e)
{
string val = ((LinkButton)sender).Text
}
There's a relatively new way of doing transparency, it's called HEXA (HEX + Alpha). It takes in 8 digits instead of 6. The last pair is Alpha. So the pattern of pairs is #RRGGBBAA. Having 4 digits also works: #RGBA
I am not sure about its browser support for now but, you can check the DRAFT Docs for more information.
§ 4.2. The RGB hexadecimal notations: #RRGGBB
The syntax of a
<hex-color>
is a<hash-token>
token whose value consists of 3, 4, 6, or 8 hexadecimal digits. In other words, a hex color is written as a hash character, "#", followed by some number of digits0-9
or lettersa-f
(the case of the letters doesn’t matter -#00ff00
is identical to#00FF00
).8 digits
The first 6 digits are interpreted identically to the 6-digit notation. The last pair of digits, interpreted as a hexadecimal number, specifies the alpha channel of the color, where
00
represents a fully transparent color andff
represent a fully opaque color.Example 3
In other words,#0000ffcc
represents the same color asrgba(0, 0, 100%, 80%)
(a slightly-transparent blue).4 digits
This is a shorter variant of the 8-digit notation, "expanded" in the same way as the 3-digit notation is. The first digit, interpreted as a hexadecimal number, specifies the red channel of the color, where
0
represents the minimum value andf
represents the maximum. The next three digits represent the green, blue, and alpha channels, respectively.
For the most part, Chrome and Firefox have started supporting this:
echo "blahblah"> txt.txt
will erase the txt and put blahblah in it's place
echo "blahblah">> txt.txt
will write blahblah on a new line in the txt
I think that both will create a new txt if none exists (I know that the first one does)
Where "txt.txt
" is written above, a file path can be inserted if wanted. e.g. C:\Users\<username>\desktop
, which will put it on their desktop.
Just ask assistance of JavaScript.
<select onchange="this.form.submit()">
...
</select>
I wrote this to compare the results of a pretty nasty view I ported from Oracle to SQL Server. It creates a pair of temp tables, #DataVariances and #SchemaVariances, with differences in (you guessed it) the data in the tables and the schema of the tables themselves.
It requires both tables have a primary key, but you could drop it into tempdb with an identity column if the source tables don't have one.
declare @TableA_ThreePartName nvarchar(max) = ''
declare @TableB_ThreePartName nvarchar(max) = ''
declare @KeyName nvarchar(max) = ''
/***********************************************************************************************
Script to compare two tables and return differneces in schema and data.
Author: Devin Lamothe 2017-08-11
***********************************************************************************************/
set nocount on
-- Split three part name into database/schema/table
declare @Database_A nvarchar(max) = (
select left(@TableA_ThreePartName,charindex('.',@TableA_ThreePartName) - 1))
declare @Table_A nvarchar(max) = (
select right(@TableA_ThreePartName,len(@TableA_ThreePartName) - charindex('.',@TableA_ThreePartName,len(@Database_A) + 2)))
declare @Schema_A nvarchar(max) = (
select replace(replace(@TableA_ThreePartName,@Database_A + '.',''),'.' + @Table_A,''))
declare @Database_B nvarchar(max) = (
select left(@TableB_ThreePartName,charindex('.',@TableB_ThreePartName) - 1))
declare @Table_B nvarchar(max) = (
select right(@TableB_ThreePartName,len(@TableB_ThreePartName) - charindex('.',@TableB_ThreePartName,len(@Database_B) + 2)))
declare @Schema_B nvarchar(max) = (
select replace(replace(@TableB_ThreePartName,@Database_B + '.',''),'.' + @Table_B,''))
-- Get schema for both tables
declare @GetTableADetails nvarchar(max) = '
use [' + @Database_A +']
select COLUMN_NAME
, DATA_TYPE
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = ''' + @Table_A + '''
and TABLE_SCHEMA = ''' + @Schema_A + '''
'
create table #Table_A_Details (
ColumnName nvarchar(max)
, DataType nvarchar(max)
)
insert into #Table_A_Details
exec (@GetTableADetails)
declare @GetTableBDetails nvarchar(max) = '
use [' + @Database_B +']
select COLUMN_NAME
, DATA_TYPE
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = ''' + @Table_B + '''
and TABLE_SCHEMA = ''' + @Schema_B + '''
'
create table #Table_B_Details (
ColumnName nvarchar(max)
, DataType nvarchar(max)
)
insert into #Table_B_Details
exec (@GetTableBDetails)
-- Get differences in table schema
select ROW_NUMBER() over (order by
a.ColumnName
, b.ColumnName) as RowKey
, a.ColumnName as A_ColumnName
, a.DataType as A_DataType
, b.ColumnName as B_ColumnName
, b.DataType as B_DataType
into #FieldList
from #Table_A_Details a
full outer join #Table_B_Details b
on a.ColumnName = b.ColumnName
where a.ColumnName is null
or b.ColumnName is null
or a.DataType <> b.DataType
drop table #Table_A_Details
drop table #Table_B_Details
select coalesce(A_ColumnName,B_ColumnName) as ColumnName
, A_DataType
, B_DataType
into #SchemaVariances
from #FieldList
-- Get differences in table data
declare @LastColumn int = (select max(RowKey) from #FieldList)
declare @RowNumber int = 1
declare @ThisField nvarchar(max)
declare @TestSql nvarchar(max)
create table #DataVariances (
TableKey nvarchar(max)
, FieldName nvarchar(max)
, TableA_Value nvarchar(max)
, TableB_Value nvarchar(max)
)
delete from #FieldList where A_DataType in ('varbinary','image') or B_DataType in ('varbinary','image')
while @RowNumber <= @LastColumn begin
set @TestSql = '
select coalesce(a.[' + @KeyName + '],b.[' + @KeyName + ']) as TableKey
, ''' + @ThisField + ''' as FieldName
, a.[' + @ThisField + '] as [TableA_Value]
, b.[' + @ThisField + '] as [TableB_Value]
from [' + @Database_A + '].[' + @Schema_A + '].[' + @Table_A + '] a
inner join [' + @Database_B + '].[' + @Schema_B + '].[' + @Table_B + '] b
on a.[' + @KeyName + '] = b.[' + @KeyName + ']
where ltrim(rtrim(a.[' + @ThisField + '])) <> ltrim(rtrim(b.[' + @ThisField + ']))
or (a.[' + @ThisField + '] is null and b.[' + @ThisField + '] is not null)
or (a.[' + @ThisField + '] is not null and b.[' + @ThisField + '] is null)
'
insert into #DataVariances
exec (@TestSql)
set @RowNumber = @RowNumber + 1
set @ThisField = (select coalesce(A_ColumnName,B_ColumnName) from #FieldList a where RowKey = @RowNumber)
end
drop table #FieldList
print 'Query complete. Select from #DataVariances to verify data integrity or #SchemaVariances to verify schemas match. Data types varbinary and image are not checked.'
Try this:
import java.net.HttpURLConnection;
URL url = new URL("http://www.myurl.com/sample.xml");
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(false);
huc.setConnectTimeout(15 * 1000);
huc.setRequestMethod("GET");
huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
huc.connect();
InputStream input = huc.getInputStream();
import org.jsoup.nodes.Document;
Document doc = null;
try {
doc = Jsoup.connect("http://www.myurl.com/sample.xml").get();
} catch (Exception e) {
//log error
}
And take look on how to use Jsoup: http://jsoup.org/cookbook/input/load-document-from-url
You can't beat the simplicity of a locked message queue. I say don't waste your time with anything more complex.
Read up on the lock statement.
EDIT
Here is an example of the Microsoft Queue object wrapped so all actions against it are thread safe.
public class Queue<T>
{
/// <summary>Used as a lock target to ensure thread safety.</summary>
private readonly Locker _Locker = new Locker();
private readonly System.Collections.Generic.Queue<T> _Queue = new System.Collections.Generic.Queue<T>();
/// <summary></summary>
public void Enqueue(T item)
{
lock (_Locker)
{
_Queue.Enqueue(item);
}
}
/// <summary>Enqueues a collection of items into this queue.</summary>
public virtual void EnqueueRange(IEnumerable<T> items)
{
lock (_Locker)
{
if (items == null)
{
return;
}
foreach (T item in items)
{
_Queue.Enqueue(item);
}
}
}
/// <summary></summary>
public T Dequeue()
{
lock (_Locker)
{
return _Queue.Dequeue();
}
}
/// <summary></summary>
public void Clear()
{
lock (_Locker)
{
_Queue.Clear();
}
}
/// <summary></summary>
public Int32 Count
{
get
{
lock (_Locker)
{
return _Queue.Count;
}
}
}
/// <summary></summary>
public Boolean TryDequeue(out T item)
{
lock (_Locker)
{
if (_Queue.Count > 0)
{
item = _Queue.Dequeue();
return true;
}
else
{
item = default(T);
return false;
}
}
}
}
EDIT 2
I hope this example helps. Remember this is bare bones. Using these basic ideas you can safely harness the power of threads.
public class WorkState
{
private readonly Object _Lock = new Object();
private Int32 _State;
public Int32 GetState()
{
lock (_Lock)
{
return _State;
}
}
public void UpdateState()
{
lock (_Lock)
{
_State++;
}
}
}
public class Worker
{
private readonly WorkState _State;
private readonly Thread _Thread;
private volatile Boolean _KeepWorking;
public Worker(WorkState state)
{
_State = state;
_Thread = new Thread(DoWork);
_KeepWorking = true;
}
public void DoWork()
{
while (_KeepWorking)
{
_State.UpdateState();
}
}
public void StartWorking()
{
_Thread.Start();
}
public void StopWorking()
{
_KeepWorking = false;
}
}
private void Execute()
{
WorkState state = new WorkState();
Worker worker = new Worker(state);
worker.StartWorking();
while (true)
{
if (state.GetState() > 100)
{
worker.StopWorking();
break;
}
}
}
1) Why is the WebSockets protocol better?
WebSockets is better for situations that involve low-latency communication especially for low latency for client to server messages. For server to client data you can get fairly low latency using long-held connections and chunked transfer. However, this doesn't help with client to server latency which requires a new connection to be established for each client to server message.
Your 48 byte HTTP handshake is not realistic for real-world HTTP browser connections where there is often several kilobytes of data sent as part of the request (in both directions) including many headers and cookie data. Here is an example of a request/response to using Chrome:
Example request (2800 bytes including cookie data, 490 bytes without cookie data):
GET / HTTP/1.1
Host: www.cnn.com
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.68 Safari/537.17
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: [[[2428 byte of cookie data]]]
Example response (355 bytes):
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 13 Feb 2013 18:56:27 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: CG=US:TX:Arlington; path=/
Last-Modified: Wed, 13 Feb 2013 18:55:22 GMT
Vary: Accept-Encoding
Cache-Control: max-age=60, private
Expires: Wed, 13 Feb 2013 18:56:54 GMT
Content-Encoding: gzip
Both HTTP and WebSockets have equivalent sized initial connection handshakes, but with a WebSocket connection the initial handshake is performed once and then small messages only have 6 bytes of overhead (2 for the header and 4 for the mask value). The latency overhead is not so much from the size of the headers, but from the logic to parse/handle/store those headers. In addition, the TCP connection setup latency is probably a bigger factor than the size or processing time for each request.
2) Why was it implemented instead of updating HTTP protocol?
There are efforts to re-engineer the HTTP protocol to achieve better performance and lower latency such as SPDY, HTTP 2.0 and QUIC. This will improve the situation for normal HTTP requests, but it is likely that WebSockets and/or WebRTC DataChannel will still have lower latency for client to server data transfer than HTTP protocol (or it will be used in a mode that looks a lot like WebSockets anyways).
Update:
Here is a framework for thinking about web protocols:
text/event-stream
MIME type. The browser API (which is fairly similar to the WebSocket API) is called the EventSource API.References:
Also i had this issue with the class library, If any one have the issue with the class library added to your main application. Just add
<startup useLegacyV2RuntimeActivationPolicy="true">
to you main application which would then be picked by the class library.
I had faced the same issue, because the jar library was copied by other Linux user(root), and the logged in user(process) did not have sufficient privilege to read the jar file content.
Your view names need to be unique even if they are pointing to the same view method, or you can add from functools import wraps and use @wraps https://docs.python.org/2/library/functools.html
Just thought I'd add that you can do this in Chrome as well:
Ctrl + Shift + I (Developer Tools) > Sources> Event Listener Breakpoints (on the right).
You can also view all events that have already been attached by simply right clicking on the element and then browsing its properties (the panel on the right).
For example:
Not sure if it's quite as powerful as the firebug option, but has been enough for most of my stuff.
Another option that is a bit different but surprisingly awesome is Visual Event: http://www.sprymedia.co.uk/article/Visual+Event+2
It highlights all of the elements on a page that have been bound and has popovers showing the functions that are called. Pretty nifty for a bookmark! There's a Chrome plugin as well if that's more your thing - not sure about other browsers.
AnonymousAndrew has also pointed out monitorEvents(window);
here
Please note that as of 2016, ReCaptcha doesn't naively support localhost anymore. From the FAQ:
localhost domains are no longer supported by default. If you wish to continue supporting them for development you can add them to the list of supported domains for your site key. Go to the admin console to update your list of supported domains. We advise to use a separate key for development and production and to not allow localhost on your production site key.
So just add localhost
to your list of domains for your site and you'll be good.
When using regular expressions from RegexBuddy's library, make sure to use the same matching modes in your own code as the regex from the library. If you generate a source code snippet on the Use tab, RegexBuddy will automatically set the correct matching options in the source code snippet. If you copy/paste the regex, you have to do that yourself.
In this case, as others pointed out, you missed the case insensitivity option.
Added some more logic to solution provided by @Andrew Burgess. Here is the full solution:
Created a action filter to get errors for ajax request:
public class ValidateAjaxAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
return;
var modelState = filterContext.Controller.ViewData.ModelState;
if (!modelState.IsValid)
{
var errorModel =
from x in modelState.Keys
where modelState[x].Errors.Count > 0
select new
{
key = x,
errors = modelState[x].Errors.
Select(y => y.ErrorMessage).
ToArray()
};
filterContext.Result = new JsonResult()
{
Data = errorModel
};
filterContext.HttpContext.Response.StatusCode =
(int)HttpStatusCode.BadRequest;
}
}
}
Added the filter to my controller method as:
[HttpPost]
// this line is important
[ValidateAjax]
public ActionResult AddUpdateData(MyModel model)
{
return Json(new { status = (result == 1 ? true : false), message = message }, JsonRequestBehavior.AllowGet);
}
Added a common script for jquery validation:
function onAjaxFormError(data) {
var form = this;
var errorResponse = data.responseJSON;
$.each(errorResponse, function (index, value) {
// Element highlight
var element = $(form).find('#' + value.key);
element = element[0];
highLightError(element, 'input-validation-error');
// Error message
var validationMessageElement = $('span[data-valmsg-for="' + value.key + '"]');
validationMessageElement.removeClass('field-validation-valid');
validationMessageElement.addClass('field-validation-error');
validationMessageElement.text(value.errors[0]);
});
}
$.validator.setDefaults({
ignore: [],
highlight: highLightError,
unhighlight: unhighlightError
});
var highLightError = function(element, errorClass) {
element = $(element);
element.addClass(errorClass);
}
var unhighLightError = function(element, errorClass) {
element = $(element);
element.removeClass(errorClass);
}
Finally added the error javascript method to my Ajax Begin form:
@model My.Model.MyModel
@using (Ajax.BeginForm("AddUpdateData", "Home", new AjaxOptions { HttpMethod = "POST", OnFailure="onAjaxFormError" }))
{
}
On socket.io >=1.0, after the connect event has triggered:
var socket = io('localhost');
var id = socket.io.engine.id
Had same issue when I had to develop a fixed length field format.
Usually we do not use line separator for binary files but For some reason our customer wished to add a line break as separator between records. They set
< record_delimiter value="\n"/ >
but this didn't work as records got two additional characters:
< record1 > \n < record2 > \n.... and so on.
Did following change and it just worked.
< record_delimiter value="\n"/> => < record_delimiter value="
"/ >
After unmarshaling Java interprets as new line character.
Long press on Google play application
Now again click on Google Play app, It will work now.
To enable svn run the TortoiseSVN installation program again, select "Modify" (Allows users to change the way features are installed) and install "command line client tools".
A static constructor looks like this
static class Foo
{
static Foo()
{
// Static initialization code here
}
}
It is executed only once when the type is first used. All classes can have static constructors, not just static classes.
that worked for me after clearing selection, BeginEdit and change the girdview rows and end the Edit Mode.
if (dgvDetails.RowCount > 0)
{
dgvDetails.ClearSelection();
dgvDetails.BeginEdit(true);
foreach (DataGridViewRow dgvr in dgvDetails.Rows)
{
dgvr.Cells["cellName"].Value = true;
}
dgvDetails.EndEdit();
}
You can take a look at Shield UI's Switch widget. It is as easy to use as this:
<input id="switch3" type="checkbox" value="" />
<script>
jQuery(function ($) {
$("#switch3").shieldSwitch({
onText: "Yes, save it",
ffText: "No, delete it",
cls: "large"
});
});
</script>
No, you can not add background color to SVG elements. You can do it programmatically with d3.
var text = d3.select("text");
var bbox = text.node().getBBox();
var padding = 2;
var rect = self.svg.insert("rect", "text")
.attr("x", bbox.x - padding)
.attr("y", bbox.y - padding)
.attr("width", bbox.width + (padding*2))
.attr("height", bbox.height + (padding*2))
.style("fill", "red");
I believe the problem is that Oracle uses the term schema slightly differently from what it generally means.
Schema in sense 2. is similar, but not the same as schema in sense 1. E.g. for an application that uses several DB accounts, a schema in sense 2 might consist of several Oracle schemas :-).
Plus schema can also mean a bunch of other, fairly unrelated things in other contexts (e.g. in mathematics).
Oracle should just have used a term like "userarea" or "accountobjects", instead of overloadin "schema"...