First of all, Take
is a completely different method. It returns an IEnumerable<T>
and not a single T
, so that's out.
Between First
and FirstOrDefault
, you should use First
when you're sure that an element exists and if it doesn't, then there's an error.
By the way, if your sequence contains default(T)
elements (e.g. null
) and you need to distinguish between being empty and the first element being null
, you can't use FirstOrDefault
.
See sys.exit
. That function will quit your program with the given exit status.
I have met the same problem as I install it globally, then I try to install it locally, and it work.
I know you have already satisfied with an answer but if you are interested to know the right approach, then this might be helpful for you. I would prefer not to mix http-response error code with the error code in the error object (confused? please continue reading a bit...).
The http response codes are standard error codes about a http response defining generic situations when response is received and varies from 1xx to 5xx ( e.g 200 OK, 408 Request timed out,504 Gateway timeout etc - http://www.restapitutorial.com/httpstatuscodes.html )
The error code in a NSError object provides very specific identification to the kind of error the object describes for a particular domain of application/product/software. For example your application may use 1000 for "Sorry, You can't update this record more than once in a day" or say 1001 for "You need manager role to access this resource"... which are specific to your domain/application logic.
For a very small application, sometimes these two concepts are merged. But they are completely different as you can see and very important & helpful to design and work with large software.
So, there can be two techniques to handle the code in better way:
completionHandler(data, httpResponse, responseError)
if nil == responseError {
successCallback(data)
} else {
failureCallback(data, responseError) // failure can have data also for standard REST request/response APIs
}
Happy coding :)
While this isn't cloning, one simple way to get your result is to use the original object as the prototype of a new one.
You can do this using Object.create
:
var obj = {a: 25, b: 50, c: 75};
var A = Object.create(obj);
var B = Object.create(obj);
A.a = 30;
B.a = 40;
alert(obj.a + " " + A.a + " " + B.a); // 25 30 40
This creates a new object in A
and B
that inherits from obj
. This means that you can add properties without affecting the original.
To support legacy implementations, you can create a (partial) shim that will work for this simple task.
if (!Object.create)
Object.create = function(proto) {
function F(){}
F.prototype = proto;
return new F;
}
It doesn't emulate all the functionality of Object.create
, but it'll fit your needs here.
the window.onload event will fire when everything is loaded, including images etc.
You would want to check the DOM ready status if you wanted your js code to execute as early as possible, but you still need to access DOM elements.
@TonyO'Hagan is comprehrensive shelljs
answer, but, I would like to highlight the synchronous version of his answer:
var shell = require('shelljs');
var output = shell.exec('netstat -rn', {silent:true}).output;
console.log(output);
I had the same question as you but I wanted to kill the gnome terminal which I was in. I read the manual on "who" and found that you can list all of the sessions logged into your computer with the '-a' option and then the '-l' option prints the system login processes.
who -la
You should get something like this. Then all you have to do is kill the process with the 'kill' command.
kill <PID>
You can initialize the array by specifying the dimensions. For example
Dim myArray(10) As Integer
Dim myArray(1 to 10) As Integer
If you are working with arrays and if this is your first time then I would recommend visiting Chip Pearson's WEBSITE.
What does this initialize to? For example, what if I want to initialize the entire array to 13?
When you want to initailize the array of 13 elements then you can do it in two ways
Dim myArray(12) As Integer
Dim myArray(1 to 13) As Integer
In the first the lower bound of the array would start with 0
so you can store 13 elements in array. For example
myArray(0) = 1
myArray(1) = 2
'
'
'
myArray(12) = 13
In the second example you have specified the lower bounds as 1
so your array starts with 1
and can again store 13 values
myArray(1) = 1
myArray(2) = 2
'
'
'
myArray(13) = 13
Wnen you initialize an array using any of the above methods, the value of each element in the array is equal to 0
. To check that try this code.
Sub Sample()
Dim myArray(12) As Integer
Dim i As Integer
For i = LBound(myArray) To UBound(myArray)
Debug.Print myArray(i)
Next i
End Sub
or
Sub Sample()
Dim myArray(1 to 13) As Integer
Dim i As Integer
For i = LBound(myArray) To UBound(myArray)
Debug.Print myArray(i)
Next i
End Sub
FOLLOWUP FROM COMMENTS
So, in this example every value would be 13. So if I had an array Dim myArray(300) As Integer, all 300 elements would hold the value 13
Like I mentioned, AFAIK, there is no direct way of achieving what you want. Having said that here is one way which uses worksheet function Rept
to create a repetitive string of 13's. Once we have that string, we can use SPLIT
using ","
as a delimiter. But note this creates a variant array but can be used in calculations.
Note also, that in the following examples myArray
will actually hold 301 values of which the last one is empty - you would have to account for that by additionally initializing this value or removing the last "," from sNum
before the Split
operation.
Sub Sample()
Dim sNum As String
Dim i As Integer
Dim myArray
'~~> Create a string with 13 three hundred times separated by comma
'~~> 13,13,13,13...13,13 (300 times)
sNum = WorksheetFunction.Rept("13,", 300)
sNum = Left(sNum, Len(sNum) - 1)
myArray = Split(sNum, ",")
For i = LBound(myArray) To UBound(myArray)
Debug.Print myArray(i)
Next i
End Sub
Using the variant array in calculations
Sub Sample()
Dim sNum As String
Dim i As Integer
Dim myArray
'~~> Create a string with 13 three hundred times separated by comma
sNum = WorksheetFunction.Rept("13,", 300)
sNum = Left(sNum, Len(sNum) - 1)
myArray = Split(sNum, ",")
For i = LBound(myArray) To UBound(myArray)
Debug.Print Val(myArray(i)) + Val(myArray(i))
Next i
End Sub
I used convertPoint method to get point from tableview and pass this point to indexPathForRowAtPoint method to get indexPath
@IBAction func newsButtonAction(sender: UIButton) {
let buttonPosition = sender.convertPoint(CGPointZero, toView: self.newsTableView)
let indexPath = self.newsTableView.indexPathForRowAtPoint(buttonPosition)
if indexPath != nil {
if indexPath?.row == 1{
self.performSegueWithIdentifier("alertViewController", sender: self);
}
}
}
If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:
Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.
Basically, you can do something like this:
function doCall(urlToCall) {
return co(function *(){
var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return finalData;
});
}
Then,
var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.
By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.
UPDATE MyTable
SET MyText = SUBSTRING(MyText, 1, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0
Use
particular_node.classList.remove("<name-of-class>")
For native javascript
Another more recent and object style way to do it :
$date = new DateTime('now');
$date->add(new DateInterval('P7D'));
It seems like sometime during the second half of 2018 many php packages such as php-mysql and phpmyadmin were removed or changed. I faced that same problem too. So you'll have to download it from another source or find out the new packages
Found a solution to Excel Mac2016 as having to paste the code into the relevant cell, enter, then go to the end of the formula within the header bar and enter the following:
Enter a formula as an array formula Image + SHIFT + RETURN or CONTROL + SHIFT + RETURN
I used the CREATE TABLE AS syntax to merge several columns and encountered the same problem. Here is an AppleScript I wrote to speed the process up.
set databasePath to "~/Documents/Databases/example.db"
set tableOne to "separate" -- Table from which you are pulling data
set tableTwo to "merged" -- Table you are creating
set {tempCol, tempColEntry, permColEntry} to {{}, {}, {}}
set permCol to {"id integer primary key"}
-- Columns are created from single items AND from the last item of a list
-- {{"a", "b", "c"}, "d", "e"} Columns "a" and "b" will be merged into a new column "c". tableTwo will have columns "c", "d", "e"
set nonCoal to {"City", "Contact", "Names", {"Address 1", "Address", "address one", "Address1", "Text4", "Address 1"}, {"E-Mail", "E-Mail Address", "Email", "Email Address", "EmailAddress", "Email"}, {"Zip", "Zip Code", "ZipCode", "Zip"}, {"Telephone", "BusinessPhone", "Phone", "Work Phone", "Telephone"}, {"St", "State", "State"}, {"Salutation", "Mr/Ms", "Mr/s", "Salutations", "Sautation", "Salutation"}}
-- Build the COALESCE statements
repeat with h from 1 to count of nonCoal
set aColumn to item h of nonCoal
if class of aColumn is not list then
if (count of words of aColumn) > 1 then set aColumn to quote & aColumn & quote
set end of tempCol to aColumn
set end of permCol to aColumn
else
set coalEntry to {}
repeat with i from 1 to count of aColumn
set coalCol to item i of aColumn as string
if (count of words of coalCol) > 1 then set coalCol to quote & coalCol & quote
if i = 1 then
set end of coalEntry to "TRIM(COALESCE(" & coalCol & ", '') || \" \" || "
else if i < ((count of aColumn) - 1) then
set end of coalEntry to "COALESCE(" & coalCol & ", '') || \" \" || "
else if i = ((count of aColumn) - 1) then
set as_Col to item (i + 1) of aColumn as string
if (count of words of as_Col) > 1 then set as_Col to quote & as_Col & quote
set end of coalEntry to ("COALESCE(" & coalCol & ", '')) AS " & as_Col) & ""
set end of permCol to as_Col
end if
end repeat
set end of tempCol to (coalEntry as string)
end if
end repeat
-- Since there are ", '' within the COALESCE statement, you can't use "TID" and "as string" to convert tempCol and permCol for entry into sqlite3. I rebuild the lists in the next block.
repeat with j from 1 to count of tempCol
if j < (count of tempCol) then
set end of tempColEntry to item j of tempCol & ", "
set end of permColEntry to item j of permCol & ", "
else
set end of tempColEntry to item j of tempCol
set end of permColEntry to item j of permCol
end if
end repeat
set end of permColEntry to ", " & item (j + 1) of permCol
set permColEntry to (permColEntry as string)
set tempColEntry to (tempColEntry as string)
-- Create the new table with an "id integer primary key" column
set createTable to "create table " & tableTwo & " (" & permColEntry & "); "
do shell script "sqlite3 " & databasePath & space & quoted form of createTable
-- Create a temporary table and then populate the permanent table
set createTemp to "create temp table placeholder as select " & tempColEntry & " from " & tableOne & "; " & "insert into " & tableTwo & " select Null, * from placeholder;"
do shell script "sqlite3 " & databasePath & space & quoted form of createTemp
--export the new table as a .csv file
do shell script "sqlite3 -header -column -csv " & databasePath & " \"select * from " & tableTwo & " ; \"> ~/" & tableTwo & ".csv"
You need to use:
:%s/,/^M/g
To get the ^M
character, press Ctrl + v followed by Enter.
Take a look at CIFS (http://www.samba.org/cifs/). It is a virtual file system you can run on your linux machine that will allow you to mount folders on your linux machine in windows using SMB.
CIFS on linux information can be found here: http://linux-cifs.samba.org/
For ASP.NET, the Load User Profile
setting needs to be set on the app pool but that's not enough. There is a hidden setting named setProfileEnvironment
in \Windows\System32\inetsrv\Config\applicationHost.config
, which for some reason is turned off by default, instead of on as described in the documentation. You can either change the default or set it on your app pool. All the methods on the Environment
class will then return proper values.
Since the event object "evt" is not passed from the parameter, is it still possible to obtain this object?
No, not reliably. IE and some other browsers make it available as window.event
(not $(window.event)
), but that's non-standard and not supported by all browsers (famously, Firefox does not).
You're better off passing the event object into the function:
<a href="#" onclick="myFunc(event, 1,2,3)">click</a>
That works even on non-IE browsers because they execute the code in a context that has an event
variable (and works on IE because event
resolves to window.event
). I've tried it in IE6+, Firefox, Chrome, Safari, and Opera. Example: http://jsbin.com/iwifu4
But your best bet is to use modern event handling:
HTML:
<a href="#">click</a>
JavaScript using jQuery (since you're using jQuery):
$("selector_for_the_anchor").click(function(event) {
// Call `myFunc`
myFunc(1, 2, 3);
// Use `event` here at the event handler level, for instance
event.stopPropagation();
});
...or if you really want to pass event
into myFunc
:
$("selector_for_the_anchor").click(function(event) {
myFunc(event, 1, 2, 3);
});
The selector can be anything that identifies the anchor. You have a very rich set to choose from (nearly all of CSS3, plus some). You could add an id
or class
to the anchor, but again, you have other choices. If you can use where it is in the document rather than adding something artificial, great.
A command like the one below will show three sections: request headers, response headers and data (separated by CRLF). It avoids technical information and syntactical noise added by curl.
curl -vs www.stackoverflow.com 2>&1 | sed '/^* /d; /bytes data]$/d; s/> //; s/< //'
The command will produce the following output:
GET / HTTP/1.1
Host: www.stackoverflow.com
User-Agent: curl/7.54.0
Accept: */*
HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=UTF-8
Location: https://stackoverflow.com/
Content-Length: 149
Accept-Ranges: bytes
Date: Wed, 16 Jan 2019 20:28:56 GMT
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: cache-bma1622-BMA
X-Cache: MISS
X-Cache-Hits: 0
X-Timer: S1547670537.588756,VS0,VE105
Vary: Fastly-SSL
X-DNS-Prefetch-Control: off
Set-Cookie: prov=e4b211f7-ae13-dad3-9720-167742a5dff8; domain=.stackoverflow.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly
<head><title>Document Moved</title></head>
<body><h1>Object Moved</h1>This document may be found <a HREF="https://stackoverflow.com/">here</a></body>
Description:
-vs
- add headers (-v) but remove progress bar (-s)2>&1
- combine stdout and stderr into single stdoutsed
- edit response produced by curl using the commands below/^* /d
- remove lines starting with '* ' (technical info)/bytes data]$/d
- remove lines ending with 'bytes data]' (technical info)s/> //
- remove '> ' prefixs/< //
- remove '< ' prefixAs indicated a standard ipv6 address is at most 45 chars, but an ipv6 address can also include an ending % followed by a "scope" or "zone" string, which has no fixed length but is generally a small positive integer or a network interface name, so in reality it can be bigger than 45 characters. Network interface names are typically "eth0", "eth1", "wlan0", so choosing 50 as the limit is likely good enough.
An int
is not null, it may be 0
if not initialized.
If you want an integer to be able to be null, you need to use Integer
instead of int
.
Integer id;
String name;
public Integer getId() { return id; }
Besides the statement if(person.equals(null))
can't be true, because if person
is null, then a NullPointerException
will be thrown. So the correct expression is if (person == null)
Check that the date you are trying to set it to lies within the allowed date range if the minDate or maxDate options are set.
First Issue: You want to run Mysql server from Mysql and from Xampp also want to browse phpmyadmin so that you can operate database.Then follow the rules:
From "Xampp/phpmyadmin" directory in config.inc.php file find the below code. And follow the given instructions below. I have tried like this and I was successful to run both localhost/phpMyAdmin on browser, MySQL Command prompt as well as MySQL query browser.
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'pma';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['controluser'] = 'user_name/root';
$cfg['Servers'][$i]['controlpass'] = 'passwaord';
And replace the above each statement with the below each corresponding code.
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'Muhammad Ashikuzzaman';
$cfg['Servers'][$i]['controluser'] = 'root';
$cfg['Servers'][$i]['controlpass'] = 'Muhammad Ashikuzzaman';
Second Issue: Way 1 : You can quit Skype first. And when Apche server is started then again you can run Skype. If you want to run Apache in another port then replace in xampp/apache/conf/httpd.conf "ServerName localhost:80" by "ServerName localhost:81" At line 184. After that even it may not work. Then replace
#Listen 0.0.0.0:80
#Listen [::]:80
Listen 80
by
#Listen 0.0.0.0:81
#Listen [::]:81
Listen 81
at line 45
Way 2 : If you want to use port 80. Then follow this. In Windows 8 “World Wide Publishing Service is using this port and stopping this service will free the port 80 and you can connect Apache using this port. To stop the service go to the “Task manager –> Services tab”, right click the “World Wide Publishing Service” and stop. If you don't find there then go to "Run > services.msc" and again find there and right click the “World Wide Publishing Service” and stop.
If you didn't find “World Wide Publishing Service” there then go to "Run>>resmon.exe>> Network Tab>>Listening Ports" and see which process is using port 80.
And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.
Create Android Application
File >> New >> Android Application
Enter Project name: android-pass-object-to-activity
Pakcage: com.hmkcode.android
Keep other defualt selections, go Next till you reach Finish
Before start creating the App we need to create POJO class “Person” which we will use to send object from one activity to another. Notice that the class is implementing Serializable interface.
Person.java
package com.hmkcode.android;
import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int age;
// getters & setters....
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
Two Layouts for Two Activities
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tvName"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Name" />
<EditText
android:id="@+id/etName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tvAge"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Age" />
<EditText
android:id="@+id/etAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</LinearLayout>
<Button
android:id="@+id/btnPassObject"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Pass Object to Another Activity" />
</LinearLayout>
activity_another.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/tvPerson"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:gravity="center_horizontal"
/>
</LinearLayout>
Two Activity Classes
1)ActivityMain.java
package com.hmkcode.android;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
Button btnPassObject;
EditText etName, etAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPassObject = (Button) findViewById(R.id.btnPassObject);
etName = (EditText) findViewById(R.id.etName);
etAge = (EditText) findViewById(R.id.etAge);
btnPassObject.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// 1. create an intent pass class name or intnet action name
Intent intent = new Intent("com.hmkcode.android.ANOTHER_ACTIVITY");
// 2. create person object
Person person = new Person();
person.setName(etName.getText().toString());
person.setAge(Integer.parseInt(etAge.getText().toString()));
// 3. put person in intent data
intent.putExtra("person", person);
// 4. start the activity
startActivity(intent);
}
}
2)AnotherActivity.java
package com.hmkcode.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class AnotherActivity extends Activity {
TextView tvPerson;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
// 1. get passed intent
Intent intent = getIntent();
// 2. get person object from intent
Person person = (Person) intent.getSerializableExtra("person");
// 3. get reference to person textView
tvPerson = (TextView) findViewById(R.id.tvPerson);
// 4. display name & age on textView
tvPerson.setText(person.toString());
}
}
While the other posters addressed why is True
does what it does, I wanted to respond to this part of your post:
I thought Python treats anything with value as True. Why is this happening?
Coming from Java, I got tripped up by this, too. Python does not treat anything with a value as True
. Witness:
if 0:
print("Won't get here")
This will print nothing because 0 is treated as False
. In fact, zero of any numeric type evaluates to False
. They also made decimal
work the way you'd expect:
from decimal import *
from fractions import *
if 0 or 0.0 or 0j or Decimal(0) or Fraction(0, 1):
print("Won't get here")
Here are the other value which evaluate to False
:
if None or False or '' or () or [] or {} or set() or range(0):
print("Won't get here")
Sources:
The cursor: pointer;
rule has been restored, so buttons will now by default have the cursor on hover:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">_x000D_
<button type="button" class="btn btn-success">Sample Button</button>
_x000D_
No, there isn't. You need to make some custom CSS for this.
If you just need a link that looks like a button (with pointer), use this:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">_x000D_
<a class="btn btn-success" href="#" role="button">Sample Button</a>
_x000D_
check your tab order and make sure the textbox is set to zero
Use This Code
@echo off
:: Get the current directory
for /f "tokens=* delims=/" %%A in ('cd') do set CURRENT_DIR=%%A
echo CURRENT_DIR%%A
(echo this To confirm this code works fine)
There is a temporary work around in Reenable (temporary) showModalDialog support in Chrome (for Windows) 37+.
Basically, create a new string in the registry at
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\EnableDeprecatedWebPlatformFeatures
Under the EnableDeprecatedWebPlatformFeatures key, create a string value with the name 1
and a value of ShowModalDialog_EffectiveUntil20150430
. To verify that the policy is enabled, visit chrome://policy
URL.
In a translation unit within the same namespace, usually at the top:
// foo.h
struct foo
{
static const std::string s;
};
// foo.cpp
const std::string foo::s = "thingadongdong"; // this is where it lives
// bar.h
namespace baz
{
struct bar
{
static const float f;
};
}
// bar.cpp
namespace baz
{
const float bar::f = 3.1415926535;
}
I'd like to expand a little bit on Pavel Minaev's answer, which you should read before reading my answer. Both solutions presented by Pavel won't compile if the member to be compared (such as id
in the question's code) is private. In this case, VS2013 throws the following error for me:
error C2248: 'Class1::id' : cannot access private member declared in class 'Class1'
As mentioned by SkyWalker in the comments on Pavel's answer, using a friend
declaration helps. If you wonder about the correct syntax, here it is:
class Class1
{
public:
Class1(int id) : id(id) {}
private:
int id;
friend struct Class1Compare; // Use this for Pavel's first solution.
friend struct std::less<Class1>; // Use this for Pavel's second solution.
};
However, if you have an access function for your private member, for example getId()
for id
, as follows:
class Class1
{
public:
Class1(int id) : id(id) {}
int getId() const { return id; }
private:
int id;
};
then you can use it instead of a friend
declaration (i.e. you compare lhs.getId() < rhs.getId()
).
Since C++11, you can also use a lambda expression for Pavel's first solution instead of defining a comparator function object class.
Putting everything together, the code could be writtem as follows:
auto comp = [](const Class1& lhs, const Class1& rhs){ return lhs.getId() < rhs.getId(); };
std::map<Class1, int, decltype(comp)> c2int(comp);
If you include the library System.Data.Entity
you can use an overload of the Include()
method which takes a lambda expression instead of a string. You can then Select()
over children with Linq expressions rather than string
paths.
return DatabaseContext.Applications
.Include(a => a.Children.Select(c => c.ChildRelationshipType));
Path
C:\Program Files\Java\jdk1.7.0_76\bin
Now you're set. Type javac
in cmd. All javac options will be displayed.
Here is a solution using Streams with Java 8
// lets assume the original list is filled with {1,1,2,3,6,3,8,7}
List<String> original = new ArrayList<>();
List<String> result = new ArrayList<>();
You just look if the frequency of this object is more than once in your list. Then call .distinct() to only have unique elements in your result
result = original.stream()
.filter(e -> Collections.frequency(original, e) > 1)
.distinct()
.collect(Collectors.toList());
// returns {1,3}
// returns only numbers which occur more than once
result = original.stream()
.filter(e -> Collections.frequency(original, e) == 1)
.collect(Collectors.toList());
// returns {2,6,8,7}
// returns numbers which occur only once
result = original.stream()
.distinct()
.collect(Collectors.toList());
// returns {1,2,3,6,8,7}
// returns the list without duplicates
This is probably simpler than you're thinking:
int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);
// ready to draw on that bitmap through that canvas
Here's a series of tutorials I've found on the topic: Drawing with Canvas Series
It looks like github has a simple UI for creating branches. I opened the branch drop-down and it prompts me to "Find or create a branch ...". Type the name of your new branch, then click the "create" button that appears.
To retrieve your new branch from github, use the standard git fetch
command.
I'm not sure this will help your underlying problem, though, since the underlying data being pushed to the server (the commit objects) is the same no matter what branch it's being pushed to.
The stated answers are correct, but I'm just sharing one additional gotcha that was applicable to my case: in addition to using setProtocol
/withProtocol
, you may have some nasty jars that won't go away even if have the right jars plus an old one:
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
Java is backward compatible, but most libraries are not. Each day that passes the more I wish shared libraries were outlawed with this lack of accountability.
java version "1.7.0_80"
Java(TM) SE Runtime Environment (build 1.7.0_80-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.80-b11, mixed mode)
To initialize 2d array with zero use the below method:
int arr[n][m] = {};
NOTE : The above method will only work to initialize with 0;
according to JAVA documentation, the JDK should be installed in this path:
/Library/Java/JavaVirtualMachines/jdkmajor.minor.macro[_update].jdk
See the uninstall JDK part at https://docs.oracle.com/javase/8/docs/technotes/guides/install/mac_jdk.html
So if you can find such folder then the JDK is installed
The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR']
or $_SERVER['REMOTE_HOST']
variables.
However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.
The below both functions are equivalent with the difference only in how and from where the values are retrieved.
getenv() is used to get the value of an environment variable in PHP.
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$_SERVER is an array that contains server variables created by the web server.
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
Well, I really don't know why the color assigned to border does not work. But you can control the border color using other border properties of the textfield. They are:
A code snippet is given below:
TextField(
enabled: false, // to trigger disabledBorder
decoration: InputDecoration(
filled: true,
fillColor: Color(0xFFF2F2F2),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(width: 1,color: Colors.red),
),
disabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(width: 1,color: Colors.orange),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(width: 1,color: Colors.green),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(width: 1,)
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(width: 1,color: Colors.black)
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
borderSide: BorderSide(width: 1,color: Colors.yellowAccent)
),
hintText: "HintText",
hintStyle: TextStyle(fontSize: 16,color: Color(0xFFB3B1B1)),
errorText: snapshot.error,
),
controller: _passwordController,
onChanged: _authenticationFormBloc.onPasswordChanged,
obscureText: false,
),
Hope it helps you.
The way to sleep your program in C++ is the Sleep(int)
method. The header file for it is #include "windows.h."
For example:
#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;
int main()
{
int x = 6000;
Sleep(x);
cout << "6 seconds have passed" << endl;
return 0;
}
The time it sleeps is measured in milliseconds and has no limit.
Second = 1000 milliseconds
Minute = 60000 milliseconds
Hour = 3600000 milliseconds
It's not an array of arrays. It's an observable of observable(s).
The following returns an observable stream of string.
requestStream
.map(function(requestUrl) {
return requestUrl;
});
While this returns an observable stream of observable stream of json
requestStream
.map(function(requestUrl) {
return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
});
flatMap
flattens the observable automatically for us so we can observe the json stream directly
Just use word-wrap:break-word;
in the css. It works.
<?php $data = "<div><p>Welcome to my PHP class, we are glad you are here</p></div>"; echo strip_tags($data); ?>
Or if you have a content coming from the database;
<?php $data = strip_tags($get_row['description']); ?>
<?=substr($data, 0, 100) ?><?php if(strlen($data) > 100) { ?>...<?php } ?>
I want to handle passing multiple lists, integer values and strings.
Helpful link => How to pass a Bash variable to Python?
def main(args):
my_args = []
for arg in args:
if arg.startswith("[") and arg.endswith("]"):
arg = arg.replace("[", "").replace("]", "")
my_args.append(arg.split(","))
else:
my_args.append(arg)
print(my_args)
if __name__ == "__main__":
import sys
main(sys.argv[1:])
Order is not important. If you want to pass a list just do as in between "["
and "]
and seperate them using a comma.
Then,
python test.py my_string 3 "[1,2]" "[3,4,5]"
Output => ['my_string', '3', ['1', '2'], ['3', '4', '5']]
, my_args
variable contains the arguments in order.
you can use:
define("PATH_ROOT", dirname(__FILE__));
include_once PATH_ROOT . "/PoliticalForum/headerSite.php";
document.getElementById('loginSubmit').submit();
or, use the same code as the onclick
handler:
changeAction('submitInput','loginForm');
document.forms['loginForm'].submit();
(Though that onclick
handler is kind of stupidly-written: document.forms['loginForm']
could be replaced with this
.)
111 means connection refused, which in turn means that your mysqld only listens to the localhost
interface.
To alter it you may want to look at the bind-address
value in the mysqld
section of your my.cnf
file.
You have to also add the "navbar-brand" class to your image a
container, also you have to include it inside the .navbar-inner
container, like so:
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="navbar-brand" href="index.html"> <img src="images/57x57x300.jpg"></a>
</div>
</div>
</div>
You should probably re-write the script to return a value rather than output it. Instead of:
a=$( script.sh ) # Now a is a string, either "success" or "Failed"
case "$a" in
success) echo script succeeded;;
Failed) echo script failed;;
esac
you would be able to do:
if script.sh > /dev/null; then
echo script succeeded
else
echo script failed
fi
It is much simpler for other programs to work with you script if they do not have to parse the output. This is a simple change to make. Just exit 0
instead of printing success
, and exit 1
instead of printing Failed
. Of course, you can also print those values as well as exiting with a reasonable return value, so that wrapper scripts have flexibility in how they work with the script.
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
best way and more simple to center an iframe on your webpage is :
<p align="center"><iframe src="http://www.google.com/" width=500 height="500"></iframe></p>
where width and height will be the size of your iframe in your html page.
You need to convert your private key to PKCS8 format using following command:
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file -nocrypt > pkcs8_key
After this your java program can read it.
In C# you can loop through the array printing each element. Note that System.Object defines a method ToString(). Any given type that derives from System.Object() can override that.
Returns a string that represents the current object.
http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx
By default the full type name of the object will be printed, though many built-in types override that default to print a more meaningful result. You can override ToString() in your own objects to provide meaningful output.
foreach (var item in myArray)
{
Console.WriteLine(item.ToString()); // Assumes a console application
}
If you had your own class Foo, you could override ToString() like:
public class Foo
{
public override string ToString()
{
return "This is a formatted specific for the class Foo.";
}
}
That's something controlled by your terminal, not by printf
.
printf
simply sends a \t
to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.
If you are not allowed to use C++'s string class (which is terrible teaching C++ imho), a raw, safe array version would look something like this.
#include <cstring>
#include <iostream>
int main()
{
char array1[] ="The dog jumps ";
char array2[] = "over the log";
char * newArray = new char[std::strlen(array1)+std::strlen(array2)+1];
std::strcpy(newArray,array1);
std::strcat(newArray,array2);
std::cout << newArray << std::endl;
delete [] newArray;
return 0;
}
This assures you have enough space in the array you're doing the concatenation to, without assuming some predefined MAX_SIZE
. The only requirement is that your strings are null-terminated, which is usually the case unless you're doing some weird fixed-size string hacking.
Edit, a safe version with the "enough buffer space" assumption:
#include <cstring>
#include <iostream>
int main()
{
const unsigned BUFFER_SIZE = 50;
char array1[BUFFER_SIZE];
std::strncpy(array1, "The dog jumps ", BUFFER_SIZE-1); //-1 for null-termination
char array2[] = "over the log";
std::strncat(array1,array2,BUFFER_SIZE-strlen(array1)-1); //-1 for null-termination
std::cout << array1 << std::endl;
return 0;
}
This generic solution should work on all rooted devices:
adb shell "su -c cat /data/data/com.android.providers.contacts/databases/contacts2.db" > contacts2.d
The command connects as shell, then executes cat
as root and collects the output into a local file.
In opposite to @guest-418 s solution, one does not have to dig for the user in question.
Plus If you get greedy and want all the db's at once (eg. for backup)
for i in `adb shell "su -c find /data -name '*.db'"`; do
mkdir -p ".`dirname $i`"
adb shell "su -c cat $i" > ".$i"
done
This adds a mysteryous question mark to the end of the filename, but it is still readable.
Arrays.asList(factors)
returns a List<int[]>
, not a List<Integer>
. Since you're doing new ArrayList
instead of new ArrayList<Integer>
you don't get a compile error for that, but create an ArrayList<Object>
which contains an int[]
and you then implicitly cast that arraylist to ArrayList<Integer>
. Of course the first time you try to use one of those "Integers" you get an exception.
Do all the necessary procedures for fixing all tables in all the databases with a simple shell script:
#!/bin/bash
mysqlcheck --all-databases
mysqlcheck --all-databases -o
mysqlcheck --all-databases --auto-repair
mysqlcheck --all-databases --analyze
You can use Linq
var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime);
Instead of adding the changes you make to resolve the conflict, you can use git reset HEAD file
to resolve the conflict without staging your changes.
You may have to run this command twice, however. Once to mark the conflict as resolved and once to unstage the changes that were staged by the conflict resolution routine.
It is possible that there should be a reset mode that does both of these things simultaneously, although there is not one now.
YouTube supports a fairly easy to use iframe and url interface to embed videos, playlists and all user uploads to your channel: https://developers.google.com/youtube/player_parameters
For example this HTML will embed a player loaded with a playlist of all the videos uploaded to your channel. Replace YOURCHANNELNAME with the actual name of your channel:
<iframe src="http://www.youtube.com/embed/?listType=user_uploads&list=YOURCHANNELNAME" width="480" height="400"></iframe>
I think the answers here are great, but I would like to add a scenario.
Several times I've wanted to take a certain amount of characters off the front of a string, without worrying about it's length. There are several ways of doing this with RIGHT() and SUBSTRING(), but they all need to know the length of the string which can sometimes slow things down.
I've use the STUFF() function instead:
SET @Result = STUFF(@Result, 1, @LengthToRemove, '')
This replaces the length of unneeded string with an empty string.
Yes, you can group by multiple columns. For example,
SELECT * FROM table
GROUP BY col1, col2
The results will first be grouped by col1, then by col2. In MySQL, column preference goes from left to right.
For XAMMP versions >=7.5.9-0 also change the DocumentRoot in file "/opt/lampp/etc/extra/httpd-ssl.conf" accordingly.
!foo.dll
in .gitignore, or (every time!) git add -f foo.dll
C++20 std::format
options <
, ^
and >
According to https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification the following should hold:
// left: "42 "
std::cout << std::format("{:<6}", 42);
// right: " 42"
std::cout << std::format("{:>6}", 42);
// center: " 42 "
std::cout << std::format("{:^6}", 42);
More information at: std::string formatting like sprintf
More recent and much cleaner: use event.key
. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
(
with the pattern
\(
. Regex.Escape
or Java's Pattern.quote
\Q
and \E
, with literal text between them.(
literally, and require \(
for capturing groups.You should get the awaiter (GetAwaiter()
) and end the wait for the completion of the asynchronous task (GetResult()
).
string code = GenerateCodeAsync().GetAwaiter().GetResult();
You can style to some degree with CSS by itself
select {
background: red;
border: 2px solid pink;
}
But this is entirely up to the browser. Some browsers are stubborn.
However, this will only get you so far, and it doesn't always look very good. For complete control, you'll need to replace a select via jQuery with a widget of your own that emulates the functionality of a select box. Ensure that when JS is disabled, a normal select box is in its place. This allows more users to use your form, and it helps with accessibility.
Set up a flux container
simple example
import alt from './../../alt.js';
class PostActions {
constructor(){
this.generateActions('setMessages');
}
setMessages(indexArray){
this.actions.setMessages(indexArray);
}
}
export default alt.createActions(PostActions);
store looks like this
class PostStore{
constructor(){
this.messages = [];
this.bindActions(MessageActions);
}
setMessages(messages){
this.messages = messages;
}
}
export default alt.createStore(PostStore);
Then every component that listens to the store can share this variable In your constructor is where you should grab it
constructor(props){
super(props);
//here is your data you get from the store, do what you want with it
var messageStore = MessageStore.getState();
}
componentDidMount() {
MessageStore.listen(this.onMessageChange.bind(this));
}
componentWillUnmount() {
MessageStore.unlisten(this.onMessageChange.bind(this));
}
onMessageChange(state){
//if the data ever changes each component listining will be notified and can do the proper processing.
}
This way, you can share you data across the app without every component having to communicate with each other.
Note that the urllib.urlencode does not always do the trick. The problem is that some services care about the order of arguments, which gets lost when you create the dictionary. For such cases, urllib.quote_plus is better, as Ricky suggested.
On Windows 8.1, IIS 8.5 the solution for me was to register 4.5 from the control panel:
Programs and Features > Turn Windows features on or off > Information Information Services > World Wide Web Services > Application Development Features > Select ASP.NET 4.5
Click OK.
Use CASE
:
SELECT
TABEL1.Id,
CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
THEN 'TRUE'
ELSE 'FALSE'
END AS NewFiled
FROM TABLE1
If TABLE2.ID
is Unique or a Primary Key, you could also use this:
SELECT
TABEL1.Id,
CASE WHEN TABLE2.ID IS NOT NULL
THEN 'TRUE'
ELSE 'FALSE'
END AS NewFiled
FROM TABLE1
LEFT JOIN Table2
ON TABLE2.ID = TABLE1.ID
The examples below refer to the following HTML snippet:
<div id="test">
Warning: This element contains <code>code</code> and <strong>strong language</strong>.
</div>
The node will be referenced by the following JavaScript:
var x = document.getElementById('test');
element.innerHTML
Sets or gets the HTML syntax describing the element's descendants
x.innerHTML
// => "
// => Warning: This element contains <code>code</code> and <strong>strong language</strong>.
// => "
This is part of the W3C's DOM Parsing and Serialization Specification. Note it's a property of Element
objects.
node.innerText
Sets or gets the text between the start and end tags of the object
x.innerText
// => "Warning: This element contains code and strong language."
innerText
was introduced by Microsoft and was for a while unsupported by Firefox. In August of 2016, innerText
was adopted by the WHATWG and was added to Firefox in v45.innerText
gives you a style-aware, representation of the text that tries to match what's rendered in by the browser this means:
innerText
applies text-transform
and white-space
rulesinnerText
trims white space between lines and adds line breaks between itemsinnerText
will not return text for invisible itemsinnerText
will return textContent
for elements that are never rendered like <style />
and ` Node
elements
node.textContent
Gets or sets the text content of a node and its descendants.
x.textContent
// => "
// => Warning: This element contains code and strong language.
// => "
While this is a W3C standard, it is not supported by IE < 9.
Node
elements
node.value
This one depends on the element that you've targeted. For the above example, x
returns an HTMLDivElement object, which does not have a value
property defined.
x.value // => null
Input tags (<input />
), for example, do define a value
property, which refers to the "current value in the control".
<input id="example-input" type="text" value="default" />
<script>
document.getElementById('example-input').value //=> "default"
// User changes input to "something"
document.getElementById('example-input').value //=> "something"
</script>
From the docs:
Note: for certain input types the returned value might not match the value the user has entered. For example, if the user enters a non-numeric value into an
<input type="number">
, the returned value might be an empty string instead.
Here's an example which shows the output for the HTML presented above:
var properties = ['innerHTML', 'innerText', 'textContent', 'value'];_x000D_
_x000D_
// Writes to textarea#output and console_x000D_
function log(obj) {_x000D_
console.log(obj);_x000D_
var currValue = document.getElementById('output').value;_x000D_
document.getElementById('output').value = (currValue ? currValue + '\n' : '') + obj; _x000D_
}_x000D_
_x000D_
// Logs property as [propName]value[/propertyName]_x000D_
function logProperty(obj, property) {_x000D_
var value = obj[property];_x000D_
log('[' + property + ']' + value + '[/' + property + ']');_x000D_
}_x000D_
_x000D_
// Main_x000D_
log('=============== ' + properties.join(' ') + ' ===============');_x000D_
for (var i = 0; i < properties.length; i++) {_x000D_
logProperty(document.getElementById('test'), properties[i]);_x000D_
}
_x000D_
<div id="test">_x000D_
Warning: This element contains <code>code</code> and <strong>strong language</strong>._x000D_
</div>_x000D_
<textarea id="output" rows="12" cols="80" style="font-family: monospace;"></textarea>
_x000D_
Two ideas:
This regex can help you to check your email-address according to all the criteria which gmail.com used.
var re = /^\w+([-+.'][^\s]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var emailFormat = re.test($("#email").val()); // This return result in Boolean type
if (emailFormat) {}
In Swift
func getFilePath() -> URL? {
let realm = try! Realm()
return realm.configuration.fileURL
}
This is the one that works for me:
SELECT DISTINCT
local_tcp_port
FROM sys.dm_exec_connections
WHERE local_tcp_port IS NOT NULL
from selenium import webdriver
driver = webdriver.Firefox()
driver.implicitly_wait(12)
driver.set_page_load_timeout(10)
def _post_selenium(self, url: str, data: dict):
input_template = '{k} <input type="text" name="{k}" id="{k}" value="{v}"><BR>\n'
inputs = ""
if data:
for k, v in data.items():
inputs += input_template.format(k=k, v=v)
html = f'<html><body>\n<form action="{url}" method="post" id="formid">\n{inputs}<input type="submit" id="inputbox">\n</form></body></html>'
html_file = os.path.join(os.getcwd(), 'temp.html')
with open(html_file, "w") as text_file:
text_file.write(html)
driver.get(f"file://{html_file}")
driver.find_element_by_id('inputbox').click()
_post_selenium("post.to.my.site.url", {"field1": "val1"})
driver.close()
I would use:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
let touch : UITouch = touches.anyObject() as UITouch
if let touchView = touch.view as? UIPickerView
{
}
}
You can use require as well:
const moduleHolder = []
function loadModules(path) {
let stat = fs.lstatSync(path)
if (stat.isDirectory()) {
// we have a directory: do a tree walk
const files = fs.readdirSync(path)
let f,
l = files.length
for (var i = 0; i < l; i++) {
f = pathModule.join(path, files[i])
loadModules(f)
}
} else {
// we have a file: load it
var controller = require(path)
moduleHolder.push(controller)
}
}
Then use your moduleHolder with dynamically loaded controllers:
loadModules(DIR)
for (const controller of moduleHolder) {
controller(app, db)
}
Python 3
from urllib.error import HTTPError
Python 2
from urllib2 import HTTPError
Just catch HTTPError
, handle it, and if it's not Error 404, simply use raise
to re-raise the exception.
See the Python tutorial.
e.g. complete example for Pyhton 2
import urllib2
from urllib2 import HTTPError
try:
urllib2.urlopen("some url")
except HTTPError as err:
if err.code == 404:
<whatever>
else:
raise
Nice to see that it have been solved in the 2016 version, but for all of those that is not on that, here are two generalized and simplified versions of the methods above.
The XML-method is shorter, but of course requires the string to allow for the xml-trick (no 'bad' chars.)
XML-Method:
create function dbo.splitString(@input Varchar(max), @Splitter VarChar(99)) returns table as
Return
SELECT Split.a.value('.', 'VARCHAR(max)') AS Data FROM
( SELECT CAST ('<M>' + REPLACE(@input, @Splitter, '</M><M>') + '</M>' AS XML) AS Data
) AS A CROSS APPLY Data.nodes ('/M') AS Split(a);
Recursive method:
create function dbo.splitString(@input Varchar(max), @Splitter Varchar(99)) returns table as
Return
with tmp (DataItem, ix) as
( select @input , CHARINDEX('',@Input) --Recu. start, ignored val to get the types right
union all
select Substring(@input, ix+1,ix2-ix-1), ix2
from (Select *, CHARINDEX(@Splitter,@Input+@Splitter,ix+1) ix2 from tmp) x where ix2<>0
) select DataItem from tmp where ix<>0
Function in action
Create table TEST_X (A int, CSV Varchar(100));
Insert into test_x select 1, 'A,B';
Insert into test_x select 2, 'C,D';
Select A,data from TEST_X x cross apply dbo.splitString(x.CSV,',') Y;
Drop table TEST_X
XML-METHOD 2: Unicode Friendly (Addition courtesy of Max Hodges)
create function dbo.splitString(@input nVarchar(max), @Splitter nVarchar(99)) returns table as
Return
SELECT Split.a.value('.', 'NVARCHAR(max)') AS Data FROM
( SELECT CAST ('<M>' + REPLACE(@input, @Splitter, '</M><M>') + '</M>' AS XML) AS Data
) AS A CROSS APPLY Data.nodes ('/M') AS Split(a);
Try to add the following configuration for surefire plugin in your pom.xml of root project:
<project>
[...]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
[...]
</project>
A number of things can cause session state to mysteriously disappear.
-
If you are using IIS 7 or 7.5, here are a few things to look for:
If you are using IIS 6, the same settings apply (for the most part but with different ways of getting to them), however getting them to log the recycles is more of a pain. Here is a link to a way to get IIS 6 to log AppPool recycle events:
-
If you are updating files on your web app, you should expect all session to be lost. That's just the nature of the beast. However, you might not expect it to happen multiple times. If you update 15 or more files (aspx, dll, etc), there is a likelyhood that you will have multiple restarts over a period of time as these pages are recompiled by users accessing the site. See these two links:
http://support.microsoft.com/kb/319947
Setting the numCompilesBeforeAppRestart to a higher number (or manually bouncing your AppPool) will eliminate this issue.
-
You can always handle Application_SessionStart and Application_SessionEnd to be notified when a session is created or ended. The HttpSessionState class also has an IsNewSession property you can check on any page request to determine if a new session is created for the active user.
-
Finally, if it's possible in your circumstance, I have used the SQL Server session mode with good success. It's not recommended if you are storing a large amount of data in it (every request loads and saves the full amount of data from SQL Server) and it can be a pain if you are putting custom objects in it (as they have to be serializable), but it has helped me in a shared hosting scenario where I couldn't configure my AppPool to not recycle couple hours. In my case, I stored limited information and it had no adverse performance effect. Add to this the fact that an existing user will reuse their SessionID by default and my users never noticed the fact that their in-memory Session was dropped by an AppPool recycle because all their state was stored in SQL Server.
Download this file :- (https://pypi.python.org/packages/1f/3b/ee6f354bcb1e28a7cd735be98f39ecf80554948284b41e9f7965951befa6/pyserial-3.2.1.tar.gz#md5=7142a421c8b35d2dac6c47c254db023d):
cd /opt
sudo tar -xvf ~/Downloads/pyserial-3.2.1.tar.gz -C .
cd /opt/pyserial-3.2.1
sudo python setup.py install
You are getting this error because you are not giving full path. (C:\Users...\file.exe) If you want to remove this error then either give full path or copy that application (you want to open) to the folder where your project(.exe) is present/saved.
#include <windows.h>
using namespace std;
int main()
{
system ("start C:\\Users\\Folder\\chrome.exe https://www.stackoverflow.com"); //for opening stackoverflow through google chrome , if chorme.exe is in that folder..
return 0;
}
When you get a NULL value from a database, the value returned is DBNull.Value on which case, you can simply call .ToString()
and it will return ""
Example:
reader["Column"].ToString()
Gets you ""
if the value returned is DBNull.Value
If the scenario is not always a database, then I'd go for an Extension method:
public static class Extensions
{
public static string EmptyIfNull(this object value)
{
if (value == null)
return "";
return value.ToString();
}
}
Usage:
string someVar = null;
someVar.EmptyIfNull();
I believe a short video showing all the details if you have Anaconda is the following for mac (it is very similar to windows users as well) just open Anaconda navigator and everything is just the same (almost!)
https://www.youtube.com/watch?v=gDzAm25CORk
Then go to jupyter notebook and code
!pip install tensorflow
Then
import tensorflow as tf
It work for me! :)
If you want to run a cron every n
minutes, there are a few possible options depending on the value of n
.
n
divides 60 (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30)
Here, the solution is straightforward by making use of the /
notation:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
m-59/n * * * * command
In the above, n
represents the value n
and m
represents a value smaller than n
or *
. This will execute the command at the minutes m,m+n,m+2n,...
n
does NOT divide 60
If n
does not divide 60, you cannot do this cleanly with cron but it is possible. To do this you need to put a test in the cron where the test checks the time. This is best done when looking at the UNIX timestamp, the total seconds since 1970-01-01 00:00:00 UTC
. Let's say we want to start to run the command the first time when Marty McFly arrived in Riverdale and then repeat it every n
minutes later.
% date -d '2015-10-21 07:28:00' +%s
1445412480
For a cronjob to run every 42
nd minute after `2015-10-21 07:28:00', the crontab would look like this:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
* * * * * minutetestcmd "2015-10-21 07:28:00" 42 && command
with minutetestcmd
defined as
#!/usr/bin/env bash
starttime=$(date -d "$1" "+%s")
# return UTC time
now=$(date "+%s")
# get the amount of minutes (using integer division to avoid lag)
minutes=$(( (now - starttime) / 60 ))
# set the modulo
modulo=$2
# do the test
(( now >= starttime )) && (( minutes % modulo == 0 ))
Remark: UNIX time is not influenced by leap seconds
Remark: cron
has no sub-second accuracy
A bit late to this question, but I created a class with all the handy methods needed to create a fully functional time trial in C#. Rather than your application config, I write the expiry time to the Windows Application Data path, and that will also remain persistent even after the program has closed (it's also tricky to find the path for the average user).
Fully documented and simple to use, I hope someone finds it useful!
public class TimeTrialManager
{
private long expiryTime=0;
private string softwareName = "";
private string userPath="";
private bool useSeconds = false;
public TimeTrialManager(string softwareName) {
this.softwareName = softwareName;
// Create folder in Windows Application Data folder for persistence:
userPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\" + softwareName + "_prefs\\";
if (!Directory.Exists(userPath)) Directory.CreateDirectory(Path.GetDirectoryName(userPath));
userPath += "expiryinfo.txt";
}
// Use this method to check if the expiry has already been created. If
// it has, you don't need to call the setExpiryDate() method ever again.
public bool expiryHasBeenStored(){
return File.Exists(userPath);
}
// Use this to set expiry as the number of days from the current time.
// This should be called just once in the program's lifetime for that user.
public void setExpiryDate(double days) {
DateTime time = DateTime.Now.AddDays(days);
expiryTime = time.ToFileTimeUtc();
storeExpiry(expiryTime.ToString() );
useSeconds = false;
}
// Like above, but set the number of seconds. This should be just used for testing
// as no sensible time trial would allow the user seconds to test the trial out:
public void setExpiryTime(double seconds) {
DateTime time = DateTime.Now.AddSeconds(seconds);
expiryTime = time.ToFileTimeUtc();
storeExpiry(expiryTime.ToString());
useSeconds = true;
}
// Check for this in a background timer or whenever else you wish to check if the time has run out
public bool trialHasExpired() {
if(!File.Exists(userPath)) return false;
if (expiryTime == 0) expiryTime = Convert.ToInt64(File.ReadAllText(userPath));
if (DateTime.Now.ToFileTimeUtc() >= expiryTime) return true; else return false;
}
// This method is optional and isn't required to use the core functionality of the class
// Perhaps use it to tell the user how long he has left to trial the software
public string expiryAsHumanReadableString(bool remaining=false) {
DateTime dt = new DateTime();
dt = DateTime.FromFileTimeUtc(expiryTime);
if (remaining == false) return dt.ToShortDateString() + " " + dt.ToLongTimeString();
else {
if (useSeconds) return dt.Subtract(DateTime.Now).TotalSeconds.ToString();
else return (dt.Subtract(DateTime.Now).TotalDays ).ToString();
}
}
// This method is private to the class, so no need to worry about it
private void storeExpiry(string value) {
try { File.WriteAllText(userPath, value); }
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
}
Here is a typical usage of the above class. Couldn't be simpler!
TimeTrialManager ttm;
private void Form1_Load(object sender, EventArgs e)
{
ttm = new TimeTrialManager("TestTime");
if (!ttm.expiryHasBeenStored()) ttm.setExpiryDate(30); // Expires in 30 days time
}
private void timer1_Tick(object sender, EventArgs e)
{
if (ttm.trialHasExpired()) { MessageBox.Show("Trial over! :("); Environment.Exit(0); }
}
If you install just the JRE, it seems to be put at:
/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
// Remove active for all items.
$('.sidebar-menu li').removeClass('active');
// highlight submenu item
$('li a[href="' + this.location.pathname + '"]').parent().addClass('active');
// Highlight parent menu item.
$('ul a[href="' + this.location.pathname + '"]').parents('li').addClass('active')
what about
$(parentSelect).nextAll().fadeOut(200, function() {
$(this).remove();
}).one(function(){
myfunction();
});
N.B. These notes are for SQL Server Express 2008 R2 (so Microsoft still haven't made this any easier). I also realise that I complicated things by installing 32-bit SQL Server Express 2005 and 64-bit SQL Server Express 2008.
I followed the steps by Josh Hinman above. Uninstalling the SQL Server Express 2005 "Workstation Components" was not enough. I required an uninstall of the 2005 Management Studio as well.
I also tried the Upgrade route that Josh Hinman suggested by clicking on the 'Upgrade from SQL Server 2000, SQL Server 2005 or SQL Server 2008'. This route never gave me the option of installing the components side-by-side it just went straight through the process of upgrading from 2005 to 2008. It completed successfully - but hadn't actually done anything. Thankfully though it hadn't harmed any existing database instances. So be warned trying that route.
<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>
tempData.push( data[index] );
I agree with the correct answer above, but.... your still not giving the index value for the data that you want to add to tempData. Without the [index] value the whole array will be added.
This is reported as broken in 1.10
http://blog.jqueryui.com/2013/01/jquery-ui-1-10-0/
phillip on January 29, 2013 at 7:36 am said: In the CDN versions, the dialog close button is missing. There’s only the button tag, the span ui-icon is missong.
I downloaded the previous version and the X for the close button shows back up.
I had the same issue and while user1732055's answer fixes the border, it removes the dropdown arrows. I solved this by removing the border from the select
element and creating a wrapper span
which has a border.
html:
<span class="select-wrapper">
<select class="form-control no-radius">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</span>
css:
select.no-radius{
border:none;
}
.select-wrapper{
border: 1px solid black;
border-radius: 0px;
}
You could use the Add-Content cmdlet. Maybe it is a little faster than the other solutions, because I don't retrieve the content of the first file.
gc .\file2.txt| Add-Content -Path .\file1.txt
I found the same problem. I did the following:
docker run -ti devops -v /tmp:/tmp /bin/bash
When I change it to
docker run -ti -v /tmp:/tmp devops /bin/bash
it works fine.
there are 2 solutions:
visit this jsfiddle
in your css you can add this:
.input-disabled{background-color:#EBEBE4;border:1px solid #ABADB3;padding:2px 1px;}
in your js do something like this:
$('#test').attr('readonly', true);
$('#test').addClass('input-disabled');
Hope this help.
Another way is using hidden input field as mentioned by some of the comments. However bear in mind that, in the backend code, you need to make sure you validate this newly hidden input at correct scenario. Hence I'm not recommend this way as it will create more bugs if its not handle properly.
You could use Map.prototype.forEach((value, key, map) => void, thisArg?) : void
instead
Use it like this:
myMap.forEach((value: boolean, key: string) => {
console.log(key, value);
});
GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.
Hiding the cursor can be done with ShowCursor().
do like this
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//codes..,.,,
Uri sound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(sound);
}
I've found that whenever I need to check if a value exists in an enum, I don't really need an enum and that a type is a better solution. So my enum in my original answer becomes:
export type ValidColors =
| "red"
| "orange"
| "yellow"
| "green"
| "blue"
| "purple";
For clarity, I like to break the values
and includes
calls onto separate lines. Here's an example:
export enum ValidColors {
Red = "red",
Orange = "orange",
Yellow = "yellow",
Green = "green",
Blue = "blue",
Purple = "purple",
}
function isValidColor(color: string): boolean {
const options: string[] = Object.values(ButtonColors);
return options.includes(color);
}
Another solution is:
SELECT * FROM TABLE1 WHERE id NOT IN (SELECT id FROM TABLE2)
onmouseover="$('.play-detail').stop().animate({'height': '84px'},'300');"
onmouseout="$('.play-detail').stop().animate({'height': '44px'},'300');"
Just put two stops -- one onmouseover and one onmouseout.
Its Working Properly
EditText et_mobile= (EditText) findViewById(R.id.edittxt);
et_mobile.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// code to execute when EditText loses focus
if (et_mobile.getText().toString().trim().length() == 0) {
CommonMethod.showAlert("Please enter name", FeedbackSubmtActivity.this);
}
}
}
});
public static void showAlert(String message, Activity context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
try {
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
}
Tags <%= %>
not works into a tag with runat="server"
. Move your code with <%= %>
into runat="server"
to an other tag (body
, head
, ...), or remove runat="server"
from container.
Any problems with the following way of doing it?
int CharToInt(const char c)
{
switch (c)
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
default:
return 0;
}
}
Generally, the answer to your question is no, you cannot define more than one externally visible function per file. You can return function handles to local functions, though, and a convenient way to do so is to make them fields of a struct. Here is an example:
function funs = makefuns
funs.fun1=@fun1;
funs.fun2=@fun2;
end
function y=fun1(x)
y=x;
end
function z=fun2
z=1;
end
And here is how it could be used:
>> myfuns = makefuns;
>> myfuns.fun1(5)
ans =
5
>> myfuns.fun2()
ans =
1
Creation of DB Link
CREATE DATABASE LINK dblinkname
CONNECT TO $usename
IDENTIFIED BY $password
USING '$sid';
(Note: sid is being passed between single quotes above. )
Example Queries for above DB Link
select * from tableA@dblinkname;
insert into tableA(select * from tableA@dblinkname);
This command:
git ls-tree --full-tree -r --name-only HEAD
lists all of the already committed files being tracked by your git repo.
Here is Kotlin version.
Thanks you :)
fun unSafeOkHttpClient() :OkHttpClient.Builder {
val okHttpClient = OkHttpClient.Builder()
try {
// Create a trust manager that does not validate certificate chains
val trustAllCerts: Array<TrustManager> = arrayOf(object : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?){}
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
})
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
if (trustAllCerts.isNotEmpty() && trustAllCerts.first() is X509TrustManager) {
okHttpClient.sslSocketFactory(sslSocketFactory, trustAllCerts.first() as X509TrustManager)
okHttpClient.hostnameVerifier { _, _ -> true }
}
return okHttpClient
} catch (e: Exception) {
return okHttpClient
}
}
I faced the error "TypeError: 'NoneType' object is not callable " but for a different issue. With the above clues, i was able to debug and got it right! The issue that i faced was : I had the custome Library written and my file wasnt recognizing it although i had mentioned it
example:
Library ../../../libraries/customlibraries/ExtendedWaitKeywords.py
the keywords from my custom library were recognized and that error was resolved only after specifying the complete path, as it was not getting the callable function.
Adding to Dmitri Chebotarev Answer,
If you want to alter multiple columns at a time , you can do it like below
DB::statement('
ALTER TABLE `events`
MODIFY `event_date` DATE NOT NULL,
MODIFY `event_start_time` TIME NOT NULL,
MODIFY `event_end_time` TIME NOT NULL;
');
Fitting an Iframe inside containers will not match the size of the container. It adds about 20px of padding. Currently there is no easy way to fix this. You need javascript (http://css-tricks.com/snippets/jquery/fit-iframe-to-content/)
Negative margins would be an easy solution.
An easy, loop-free alternative is to use the horizontalalignment
Text property as a keyword argument to xticks
[1]. In the below, at the commented line, I've forced the xticks
alignment to be "right".
n=5
x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]
fig, ax = plt.subplots()
ax.plot(x,y, 'o-')
plt.xticks(
[0,1,2,3,4],
["this label extends way past the figure's left boundary",
"bad motorfinger", "green", "in the age of octopus diplomacy", "x"],
rotation=45,
horizontalalignment="right") # here
plt.show()
(yticks
already aligns the right edge with the tick by default, but for xticks
the default appears to be "center".)
[1] You find that described in the xticks documentation if you search for the phrase "Text properties".
The DragListView lib does this really neat with very nice support for custom animations such as elevation animations. It is also still maintained and updated on a regular basis.
Here is how you use it:
1: Add the lib to gradle first
dependencies {
compile 'com.github.woxthebox:draglistview:1.2.1'
}
2: Add list from xml
<com.woxthebox.draglistview.DragListView
android:id="@+id/draglistview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
3: Set the drag listener
mDragListView.setDragListListener(new DragListView.DragListListener() {
@Override
public void onItemDragStarted(int position) {
}
@Override
public void onItemDragEnded(int fromPosition, int toPosition) {
}
});
4: Create an adapter overridden from DragItemAdapter
public class ItemAdapter extends DragItemAdapter<Pair<Long, String>, ItemAdapter.ViewHolder>
public ItemAdapter(ArrayList<Pair<Long, String>> list, int layoutId, int grabHandleId, boolean dragOnLongPress) {
super(dragOnLongPress);
mLayoutId = layoutId;
mGrabHandleId = grabHandleId;
setHasStableIds(true);
setItemList(list);
}
5: Implement a viewholder that extends from DragItemAdapter.ViewHolder
public class ViewHolder extends DragItemAdapter.ViewHolder {
public TextView mText;
public ViewHolder(final View itemView) {
super(itemView, mGrabHandleId);
mText = (TextView) itemView.findViewById(R.id.text);
}
@Override
public void onItemClicked(View view) {
}
@Override
public boolean onItemLongClicked(View view) {
return true;
}
}
For more detailed info go to https://github.com/woxblom/DragListView
This also works in Internet Explorer, but auto margins do not.
.centered {
position: absolute;
display: inline-block;
left: -500px;
width: 1000px;
margin: 0 50%;
}
Map reduce is a framework that was developed to process massive amounts of data efficiently. For example, if we have 1 million records in a dataset, and it is stored in a relational representation - it is very expensive to derive values and perform any sort of transformations on these.
For Example In SQL, Given the Date of Birth, to find out How many people are of age > 30 for a million records would take a while, and this would only increase in order of magnitute when the complexity of the query increases. Map Reduce provides a cluster based implementation where data is processed in a distributed manner
Here is a wikipedia article explaining what map-reduce
is all about
Another good example is Finding Friends via map reduce can be a powerful example to understand the concept, and a well used use-case.
Personally, found this link quite useful to understand the concept
Copying the explanation provided in the blog (In case the link goes stale)
Finding Friends
MapReduce is a framework originally developed at Google that allows for easy large scale distributed computing across a number of domains. Apache Hadoop is an open source implementation.
I'll gloss over the details, but it comes down to defining two functions: a map function and a reduce function. The map function takes a value and outputs key:value pairs. For instance, if we define a map function that takes a string and outputs the length of the word as the key and the word itself as the value then map(steve) would return 5:steve and map(savannah) would return 8:savannah. You may have noticed that the map function is stateless and only requires the input value to compute it's output value. This allows us to run the map function against values in parallel and provides a huge advantage. Before we get to the reduce function, the mapreduce framework groups all of the values together by key, so if the map functions output the following key:value pairs:
3 : the 3 : and 3 : you 4 : then 4 : what 4 : when 5 : steve 5 : where 8 : savannah 8 : research
They get grouped as:
3 : [the, and, you] 4 : [then, what, when] 5 : [steve, where] 8 : [savannah, research]
Each of these lines would then be passed as an argument to the reduce function, which accepts a key and a list of values. In this instance, we might be trying to figure out how many words of certain lengths exist, so our reduce function will just count the number of items in the list and output the key with the size of the list, like:
3 : 3 4 : 3 5 : 2 8 : 2
The reductions can also be done in parallel, again providing a huge advantage. We can then look at these final results and see that there were only two words of length 5 in our corpus, etc...
The most common example of mapreduce is for counting the number of times words occur in a corpus. Suppose you had a copy of the internet (I've been fortunate enough to have worked in such a situation), and you wanted a list of every word on the internet as well as how many times it occurred.
The way you would approach this would be to tokenize the documents you have (break it into words), and pass each word to a mapper. The mapper would then spit the word back out along with a value of
1
. The grouping phase will take all the keys (in this case words), and make a list of 1's. The reduce phase then takes a key (the word) and a list (a list of 1's for every time the key appeared on the internet), and sums the list. The reducer then outputs the word, along with it's count. When all is said and done you'll have a list of every word on the internet, along with how many times it appeared.Easy, right? If you've ever read about mapreduce, the above scenario isn't anything new... it's the "Hello, World" of mapreduce. So here is a real world use case (Facebook may or may not actually do the following, it's just an example):
Facebook has a list of friends (note that friends are a bi-directional thing on Facebook. If I'm your friend, you're mine). They also have lots of disk space and they serve hundreds of millions of requests everyday. They've decided to pre-compute calculations when they can to reduce the processing time of requests. One common processing request is the "You and Joe have 230 friends in common" feature. When you visit someone's profile, you see a list of friends that you have in common. This list doesn't change frequently so it'd be wasteful to recalculate it every time you visited the profile (sure you could use a decent caching strategy, but then I wouldn't be able to continue writing about mapreduce for this problem). We're going to use mapreduce so that we can calculate everyone's common friends once a day and store those results. Later on it's just a quick lookup. We've got lots of disk, it's cheap.
Assume the friends are stored as Person->[List of Friends], our friends list is then:
A -> B C D B -> A C D E C -> A B D E D -> A B C E E -> B C D
Each line will be an argument to a mapper. For every friend in the list of friends, the mapper will output a key-value pair. The key will be a friend along with the person. The value will be the list of friends. The key will be sorted so that the friends are in order, causing all pairs of friends to go to the same reducer. This is hard to explain with text, so let's just do it and see if you can see the pattern. After all the mappers are done running, you'll have a list like this:
For map(A -> B C D) : (A B) -> B C D (A C) -> B C D (A D) -> B C D For map(B -> A C D E) : (Note that A comes before B in the key) (A B) -> A C D E (B C) -> A C D E (B D) -> A C D E (B E) -> A C D E For map(C -> A B D E) : (A C) -> A B D E (B C) -> A B D E (C D) -> A B D E (C E) -> A B D E For map(D -> A B C E) : (A D) -> A B C E (B D) -> A B C E (C D) -> A B C E (D E) -> A B C E And finally for map(E -> B C D): (B E) -> B C D (C E) -> B C D (D E) -> B C D Before we send these key-value pairs to the reducers, we group them by their keys and get: (A B) -> (A C D E) (B C D) (A C) -> (A B D E) (B C D) (A D) -> (A B C E) (B C D) (B C) -> (A B D E) (A C D E) (B D) -> (A B C E) (A C D E) (B E) -> (A C D E) (B C D) (C D) -> (A B C E) (A B D E) (C E) -> (A B D E) (B C D) (D E) -> (A B C E) (B C D)
Each line will be passed as an argument to a reducer. The reduce function will simply intersect the lists of values and output the same key with the result of the intersection. For example, reduce((A B) -> (A C D E) (B C D)) will output (A B) : (C D) and means that friends A and B have C and D as common friends.
The result after reduction is:
(A B) -> (C D) (A C) -> (B D) (A D) -> (B C) (B C) -> (A D E) (B D) -> (A C E) (B E) -> (C D) (C D) -> (A B E) (C E) -> (B D) (D E) -> (B C)
Now when D visits B's profile, we can quickly look up
(B D)
and see that they have three friends in common,(A C E)
.
ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).
In a comment you said
"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"
Well, your code does this:
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?
ORA-06510: PL/SQL: unhandled user-defined exception
If so, all you need to do is add an exception block to handle the error. Perhaps:
PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
vSOME_EX EXCEPTION;
BEGIN
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
ELSE
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
END IF;
exception
when vsome_ex then
raise_application_error(-20000
, 'This is not a valid table: M'||pNum||'GR');
END PX;
The documentation covers handling PL/SQL exceptions in depth.
The question is old but I felt the best answer hadn't been given, yet.
Is there an
UPDATE
syntax ... without specifying the column names?
You don't need to know any column names except for some unique column(s) to join on (id
in the example). Works reliably for any possible corner case I can think of.
This is specific to PostgreSQL. I am building dynamic code based on the the information_schema, in particular the table information_schema.columns
, which is defined in the SQL standard and most major RDBMS (except Oracle) have it. But a DO
statement with PL/pgSQL code executing dynamic SQL is totally non-standard PostgreSQL syntax.
DO
$do$
BEGIN
EXECUTE (
SELECT
'UPDATE b
SET (' || string_agg( quote_ident(column_name), ',') || ')
= (' || string_agg('a.' || quote_ident(column_name), ',') || ')
FROM a
WHERE b.id = 123
AND a.id = b.id'
FROM information_schema.columns
WHERE table_name = 'a' -- table name, case sensitive
AND table_schema = 'public' -- schema name, case sensitive
AND column_name <> 'id' -- all columns except id
);
END
$do$;
Assuming a matching column in b
for every column in a
, but not the other way round. b
can have additional columns.
WHERE b.id = 123
is optional, to update a selected row.
Related answers with more explanation:
You still need to know the list of column names that both tables share. With a syntax shortcut for updating multiple columns - shorter than what other answers suggested so far in any case.
UPDATE b
SET ( column1, column2, column3)
= (a.column1, a.column2, a.column3)
FROM a
WHERE b.id = 123 -- optional, to update only selected row
AND a.id = b.id;
This syntax was introduced with Postgres 8.2 in 2006, long before the question was asked. Details in the manual.
Related:
B
If all columns of A
are defined NOT NULL
(but not necessarily B
),
and you know the column names of B
(but not necessarily A
).
UPDATE b
SET (column1, column2, column3, column4)
= (COALESCE(ab.column1, b.column1)
, COALESCE(ab.column2, b.column2)
, COALESCE(ab.column3, b.column3)
, COALESCE(ab.column4, b.column4)
)
FROM (
SELECT *
FROM a
NATURAL LEFT JOIN b -- append missing columns
WHERE b.id IS NULL -- only if anything actually changes
AND a.id = 123 -- optional, to update only selected row
) ab
WHERE b.id = ab.id;
The NATURAL LEFT JOIN
joins a row from b
where all columns of the same name hold same values. We don't need an update in this case (nothing changes) and can eliminate those rows early in the process (WHERE b.id IS NULL
).
We still need to find a matching row, so b.id = ab.id
in the outer query.
db<>fiddle here
Old sqlfiddle.
This is standard SQL except for the FROM
clause.
It works no matter which of the columns are actually present in A
, but the query cannot distinguish between actual NULL values and missing columns in A
, so it is only reliable if all columns in A
are defined NOT NULL
.
There are multiple possible variations, depending on what you know about both tables.
The CSV "standard" (such as it is) does not dictate how comments should be handled, no, it's up to the application to establish a convention and stick with it.
Another example is available here:
Sending a JSON to server and retrieving a JSON in return, without JQuery
Which is the same as jans answer, but also checks the servers response by setting a onreadystatechange callback on the XMLHttpRequest.
If, rather than writing new code to trim a string, you're looking at existing code that calls "strip()" and wondering why it isn't working, you might want to check whether it attempts to include something like the prototypejs framework, and make sure it's actually getting loaded.
That framework adds a strip function to all String objects, but if e.g. you upgraded it and your web pages are still referring to the old .js file it'll of course not work.
maybe you want to take a look java.util.Stack
class.
it has push, pop methods. and implemented List interface.
for shift/unshift, you can reference @Jon's answer.
however, something of ArrayList you may want to care about , arrayList is not synchronized. but Stack is. (sub-class of Vector). If you have thread-safe requirement, Stack may be better than ArrayList.
Try this, with strings:
set "var=string1string2string3"
and with string variables:
set "var=%string1%%string2%%string3%"
querySelector
is of w3c Selector API
getElementBy
is of w3c DOM API
IMO the most notable difference is that the return type of querySelectorAll
is a static node list and for getElementsBy
it's a live node list. Therefore the looping in demo 2 never ends because lis
is live and updates itself during each iteration.
// Demo 1 correct
var ul = document.querySelectorAll('ul')[0],
lis = ul.querySelectorAll("li");
for(var i = 0; i < lis.length ; i++){
ul.appendChild(document.createElement("li"));
}
// Demo 2 wrong
var ul = document.getElementsByTagName('ul')[0],
lis = ul.getElementsByTagName("li");
for(var i = 0; i < lis.length ; i++){
ul.appendChild(document.createElement("li"));
}
You're not actually using promises here. Parse lets you use callbacks or promises; your choice.
To use promises, do the following:
query.find().then(function() {
console.log("success!");
}, function() {
console.log("error");
});
Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then()
call. So far this would be exactly the same as regular callbacks.
To actually make good use of promises is when you chain them, like this:
query.find().then(function() {
console.log("success!");
return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
console.log("error");
}).then(function() {
console.log("success on second callback!");
}, function() {
console.log("error on second callback");
});
Maybe
my_qstring.toStdString().c_str();
or safer, as Federico points out:
std::string str = my_qstring.toStdString();
const char* p = str.c_str();
It's far from optimal, but will do the work.
#!/usr/bin/python
import sys
import os
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 50000
try:
s.bind((socket.gethostname() , port))
except socket.error as msg:
print(str(msg))
s.listen(10)
conn, addr = s.accept()
print 'Got connection from'+addr[0]+':'+str(addr[1]))
while 1:
msg = s.recv(1024)
print +addr[0]+, ' >> ', msg
msg = raw_input('SERVER >>'),host
s.send(msg)
s.close()
public static void main(String[] args) {
System.out.println(longestPalindromeString("9912333321456"));
}
static public String intermediatePalindrome(String s, int left, int right) {
if (left > right) return null;
while (left >= 0 && right < s.length()
&& s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return s.substring(left + 1, right);
}
public static String longestPalindromeString(String s) {
if (s == null) return null;
String longest = s.substring(0, 1);
for (int i = 0; i < s.length() - 1; i++) {
//odd cases like 121
String palindrome = intermediatePalindrome(s, i, i);
if (palindrome.length() > longest.length()) {
longest = palindrome;
}
//even cases like 1221
palindrome = intermediatePalindrome(s, i, i + 1);
if (palindrome.length() > longest.length()) {
longest = palindrome;
}
}
return longest;
}
In Xcode 7 you can have multiple storyBoards. It will be better if you can keep the Login flow in a separate storyboard.
This can be done using SELECT VIEWCONTROLLER > Editor > Refactor to Storyboard
And here is the Swift version for setting a view as the RootViewContoller-
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window!.rootViewController = newRootViewController
let rootViewController: UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LoginViewController")
DrawerLayout Properties
android:layout_gravity="right|end"
and tools:openDrawer="end"
NavigationView Property
android:layout_gravity="end"
XML Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:layout_gravity="right|end"
tools:openDrawer="end">
<include layout="@layout/content_main" />
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="end"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
Java Code
// Appropriate Click Event or Menu Item Click Event
if (drawerLayout.isDrawerOpen(GravityCompat.END))
{
drawerLayout.closeDrawer(GravityCompat.END);
}
else
{
drawerLayout.openDrawer(GravityCompat.END);
}
//With Toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Gravity.END or Gravity.RIGHT
if (drawer.isDrawerOpen(Gravity.END)) {
drawer.closeDrawer(Gravity.END);
} else {
drawer.openDrawer(Gravity.END);
}
}
});
//...
}
It's because the CPU doesn't have so many cache misses (where it has to wait for the array data to come from the RAM chips). It would be interesting for you to adjust the size of the arrays continually so that you exceed the sizes of the level 1 cache (L1), and then the level 2 cache (L2), of your CPU and plot the time taken for your code to execute against the sizes of the arrays. The graph shouldn't be a straight line like you'd expect.
Edit: I missed the multi-dimensional aspect of this question, so I'm leaving this here in case it helps people compare one-dimensional arrays
It's an old question, but I was having issues with the speed of using .sort()
or sortBy()
, so I used this instead:
function arraysContainSameStrings(array1: string[], array2: string[]): boolean {
return (
array1.length === array2.length &&
array1.every((str) => array2.includes(str)) &&
array2.every((str) => array1.includes(str))
)
}
It was intended to fail fast, and for my purposes works fine.
The good thing is, this one is really easily and deterministically to analyze: Either, the msi package is really not installed on the system or you're doing something wrong. Of course the correct call is:
msiexec /x {A4BFF20C-A21E-4720-88E5-79D5A5AEB2E8}
(Admin rights needed of course- With curly braces without any quotes here- quotes are only needed, if paths or values with blank are specified in the commandline.)
If the message is: "This action is only valid for products that are currently installed", then this is true. Either the package with this ProductCode is not installed or there is a typo.
To verify where the fault is:
First try to right click on the (probably) installed .msi file itself. You will see (besides "Install" and "Repair") an Uninstall entry. Click on that.
a) If that uninstall works, your msi has another ProductCode than you expect (maybe you have the wrong WiX source or your build has dynamic logging where the ProductCode changes).
b) If that uninstall gives the same "...only valid for products already installed" the package is not installed (which is obviously a precondition to be able to uninstall it).
If 1.a) was the case, you can look for the correct ProductCode of your package, if you open your msi file with Orca, Insted or another editor/tool. Just google for them. Look there in the table with the name "Property" and search for the string "ProductCode" in the first column. In the second column there is the correct value.
There are no other possibilities.
Just a suggestion for the used commandline: I would add at least the "/qb" for a simple progress bar or "/qn" parameter (the latter for complete silent uninstall, but makes only sense if you are sure it works).
String strLong = Long.toString(longNumber);
Simple and works fine :-)
I found something I did wrong, install the Apache and MySQL services. Click on the WAMP logo, goto Apache -> Service -> Install Service, after that Apache -> Service -> Start/Resume Service. Do the same for MySQL and it will turn green.
USING POSTFIX
1: install software
Debian and Ubuntu:
apt-get update && apt-get install postfix mailutils
OpenSUSE:
zypper update && zypper install postfix mailx cyrus-sasl
Fedora:
dnf update && dnf install postfix mailx
CentOS:
yum update && yum install postfix mailx cyrus-sasl cyrus-sasl-plain
Arch Linux:
pacman -Sy postfix mailutils
FreeBSD:
portsnap fetch extract update
cd /usr/ports/mail/postfix
make config
in configaration select SASL support
make install clean
pkg install mailx
2. Configure Gmail
/etc/postfix. Create or edit the password file:
vim /etc/postfix/sasl_passwd
i m using vim u can use any file editer like nano, cat .....
>Ubuntu, Fedora, CentOS,Debian, OpenSUSE, Arch Linux:
add this
where user replace with your mailname and password is your gmail password
[smtp.gmail.com]:587 [email protected]:password
Save and close the file and Make it accessible only by root: becouse its an sensitive content which contains ur password
chmod 600 /usr/local/etc/postfix/sasl_passwd
>FreeBSD:
directory /usr/local/etc/postfix.
vim /usr/local/etc/postfix/sasl_passwd
Add the line:
[smtp.gmail.com]:587 [email protected]:password
Save and Make it accessible only by root:
chmod 600 /usr/local/etc/postfix/sasl_passwd
3. Postfix configuration
configuration file main.cf
6 parameters we must set in the Postfix
Ubuntu, Arch Linux,Debian:
edit
vim /etc/postfix/main.cf
modify the following values:
relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
smtp_sasl_security_options which in configuration will be set to empty, to ensure that no Gmail-incompatible security options are used.
save and close
as like for
OpenSUSE:
vim /etc/postfix/main.cf
modify
relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/ca-bundle.pem
it also requires configuration of file master.cf
modify:
vim /etc/postfix/master.cf
as by uncommenting this line(remove #)
#tlsmgr unix - - n 1000? 1 tlsmg
save and close
Fedora, CentOS:
vim /etc/postfix/main.cf
modify
relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-bundle.crt
FreeBSD:
vim /usr/local/etc/postfix/main.cf
modify:
relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/usr/local/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/mail/certs/cacert.pem
save and close this
4. Process Password File:
Ubuntu, Fedora, CentOS, OpenSUSE, Arch Linux,Debian:
postmap /etc/postfix/sasl_passwd
for freeBSD
postmap /usr/local/etc/postfix/sasl_passwd
4.1) Restart postfix
Ubuntu, Fedora, CentOS, OpenSUSE, Arch Linux,Debian:
systemctl restart postfix.service
for FreeBSD:
service postfix onestart
nano /etc/rc.conf
add
postfix_enable=YES
save then run to start
service postfix start
5. Enable "Less Secure Apps" In Gmail using help of below link
https://support.google.com/accounts/answer/6010255
6. Send A Test Email
mail -s "subject" [email protected]
press enter
add body of mail as your wish press enter then press ctrl+d for proper termination
if it not working check the all steps again and check if u enable "less secure app" in your gmail
then restart postfix if u modify anything in that
for shell script create the .sh file and add 6 step command as your requirement
for example just for a sample
#!/bin/bash
REALVALUE=$(df / | grep / | awk '{ print $5}' | sed 's/%//g')
THRESHOLD=80
if [ "$REALVALUE" -gt "$THRESHOLD" ] ; then
mail -s 'Disk Space Alert' [email protected] << EOF
Your root partition remaining free space is critically low. Used: $REALVALUE%
EOF
fi
The script sends an email when the disk usage rises above the percentage specified by the THRESHOLD varialbe (80% here).
maybe this help :
declare
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'
set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + '''
'
exec sp_executesql @statement;
this is same as below :
select @text1 + ' beautifull ' + @text2
In Notepad++ you can select few lines and use CTRL+Q which will automaticaly make block comments for selected lines.
Remember, you are NOT allowed to do this.
class foo():
def print_hello(self):
print("Hello") # This next line will produce an ERROR!
self.print_hello() # <---- it calls a class function, inside a class,
# but outside a class function. Not allowed.
You must call a class function from either outside the class, or from within a function in that class.
In Nexus version 3.13.0-01, the id
in the POM's distributionManagement/repository
section MUST match the servers/server/id
and mirrors/mirror/id
in your maven settings.xml. I just replaced nexus v3.10.4 (with 3.13.0-01) and it wasn't needed to match for 3.10.4.
The problem is that /var/www
doesn't exist either, and mkdir
isn't recursive by default -- it expects the immediate parent directory to exist.
Use:
mkdir -p /var/www/app
...or install a package that creates a /var/www
prior to reaching this point in your Dockerfile.
One of the main purposes of integration testing with MockMvc
is to verify that model objects are correclty populated with form data.
In order to do it you have to pass form data as they're passed from actual form (using .param()
). If you use some automatic conversion from NewObject
to from data, your test won't cover particular class of possible problems (modifications of NewObject
incompatible with actual form).
Was having a similar issue with a ListBox wanting to open a window (Different View) with the SelectedItem as the context (in my case, so I can edit it).
The three options I've found are: 1. Code Behind 2. Using Attached Behaviors 3. Using Blend's i:Interaction and EventToCommand using MVVM-Light.
I went with the 3rd option, and it looks something along these lines:
<ListBox x:Name="You_Need_This_Name"
ItemsSource="{Binding Your_Collection_Name_Here}"
SelectedItem="{Binding Your_Property_Name_Here, UpdateSourceTrigger=PropertyChanged}"
... rest of your needed stuff here ...
>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<Command:EventToCommand Command="{Binding Your_Command_Name_Here}"
CommandParameter="{Binding ElementName=You_Need_This_Name,Path=SelectedItem}" />
</i:EventTrigger>
</i:Interaction.Triggers>
That's about it ... when you double click on the item you want, your method on the ViewModel will be called with the SelectedItem as parameter, and you can do whatever you want there :)
This command helped me on linux mint when i had exact same problem
gcc filename.c -L/usr/include -lreadline -o filename
You could use alias if you compile it many times Forexample:
alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'
For:
2 mod 4
We can use this little formula I came up with after thinking a bit, maybe it's already defined somewhere I don't know but works for me, and its really useful.
A mod B = C
where C is the answer
K * B - A = |C|
where K is how many times B fits in A
2 mod 4
would be:
0 * 4 - 2 = |C|
C = |-2| => 2
Hope it works for you :)
So, I had this code:
<div class="dropdown-select-wrapper" *ngIf="contentData">
<button mat-stroked-button [disableRipple]="true" class="mat-button" (click)="openSelect()" [ngClass]="{'only-icon': !contentData?.buttonText?.length}">
<i *ngIf="contentData.iconClassInfo" class="dropdown-icon {{contentData.iconClassInfo.name}}"></i>
<span class="button-text" *ngIf="contentData.buttonText">{{contentData.buttonText}}</span>
</button>
<mat-select class="small-dropdown-select" [formControl]="theFormControl" #buttonSelect (selectionChange)="onSelect(buttonSelect.selected)" (click)="$event.stopPropagation();">
<mat-option *ngFor="let option of options" [ngClass]="{'selected-option': buttonSelect.selected?.value === option[contentData.optionsStructure.valName]}" [disabled]="buttonSelect.selected?.value === option[contentData.optionsStructure.valName] && contentData.optionSelectedWillDisable" [value]="option[contentData.optionsStructure.valName]">
{{option[contentData.optionsStructure.keyName]}}
</mat-option>
</mat-select>
</div>
Here I was using standalone formControl, and I was getting the error we are talking about, which made no sense for me, since I wasn't working with formgroups or formarrays... it only disappeared when I added the *ngIf to the select it self, so is not being used before it actually exists. That's what solved the issue in my case.
<mat-select class="small-dropdown-select" [formControl]="theFormControl" #buttonSelect (selectionChange)="onSelect(buttonSelect.selected)" (click)="$event.stopPropagation();" *ngIf="theFormControl">
<mat-option *ngFor="let option of options" [ngClass]="{'selected-option': buttonSelect.selected?.value === option[contentData.optionsStructure.valName]}" [disabled]="buttonSelect.selected?.value === option[contentData.optionsStructure.valName] && contentData.optionSelectedWillDisable" [value]="option[contentData.optionsStructure.valName]">
{{option[contentData.optionsStructure.keyName]}}
</mat-option>
</mat-select>
Well by doing the above you open yourself to run time errors, unless you are happy to accept that your arraylists can contains both strings and integers and elephants.
Eclipse returns an error because it does not want you to be unaware of the fact that by specifying no type for the generic parameter you are opening yourself up for run time errors. At least with the other two examples you know that you can have objects in your Arraylist and since Inetegers and Strings are both objects Eclipse doesn't warn you.
Either code 2 or 3 are ok. But if you know you will have either only ints or only strings in your arraylist then I would do
ArrayList<Integer> arr = new ArrayList<Integer>();
or
ArrayList<String> arr = new ArrayList<String>();
respectively.
If your source "file" is split up among multiple files (maybe as the result of map-reduce) that live in the same directory tree, you can copy that to a local file with:
hadoop fs -getmerge /hdfs/source/dir_root/ local/destination
I never had time to play with clojure. But for scala vs groovy, this is words from James Strachan - Groovy creator
"Though my tip though for the long term replacement of javac is Scala. I'm very impressed with it! I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy."
You can read the whole story here
import UIKit
import AVFoundation
class ViewController: UIViewController{
var player: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func notePressed(_ sender: UIButton) {
guard let url = Bundle.main.url(forResource: "note1", withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory((AVAudioSession.Category.playback), mode: .default, options: [])
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) *//
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
}
try:
if val is None: # The variable
print('It is None')
except NameError:
print ("This variable is not defined")
else:
print ("It is defined and has a value")
JWT is an open standard that defines a compact and self-contained way for securely transmitting information between parties. It is an authentication protocol where we allow encoded claims (tokens) to be transferred between two parties (client and server) and the token is issued upon the identification of a client. With each subsequent request we send the token.
Whereas OAuth2 is an authorization framework, where it has a general procedures and setups defined by the framework. JWT can be used as a mechanism inside OAuth2.
You can read more on this here
You can write your own rule!
// add the rule here
$.validator.addMethod("valueNotEquals", function(value, element, arg){
return arg !== value;
}, "Value must not equal arg.");
// configure your validation
$("form").validate({
rules: {
SelectName: { valueNotEquals: "default" }
},
messages: {
SelectName: { valueNotEquals: "Please select an item!" }
}
});
I obtained much better results with wxPython than tkinter, as suggested in this answer to a later duplicate question:
https://stackoverflow.com/a/9319832
The wxPython version produced the file dialog that looked the same as the open file dialog from just about any other application on my OpenSUSE Tumbleweed installation with the xfce desktop, whereas tkinter produced something cramped and hard to read with an unfamiliar side-scrolling interface.
>>> [5] * 4
[5, 5, 5, 5]
Be careful when the item being repeated is a list. The list will not be cloned: all the elements will refer to the same list!
>>> x=[5]
>>> y=[x] * 4
>>> y
[[5], [5], [5], [5]]
>>> y[0][0] = 6
>>> y
[[6], [6], [6], [6]]
You need to use the SUBTOTAL function. The SUBTOTAL function ignores rows that have been excluded by a filter.
The formula would look like this:
=SUBTOTAL(9,B1:B20)
The function number 9, tells it to use the SUM function on the data range B1:B20.
If you are 'filtering' by hiding rows, the function number should be updated to 109.
=SUBTOTAL(109,B1:B20)
The function number 109 is for the SUM function as well, but hidden rows are ignored.
Check the syntax of your connection string in the web.config. It should be something like ConnectionString="Data Source=C:\DataDictionary\NerdDinner.sdf"
Try Adminer. The whole application is in one PHP file, which means that the deployment is as easy as it can get. It's more powerful than phpMyAdmin; it can edit views, procedures, triggers, etc.
Adminer is also a universal tool, it can connect to MySQL, PostgreSQL, SQLite, MS SQL, Oracle, SimpleDB, Elasticsearch and MongoDB.
You should definitely give it a try.
You can install on Ubuntu with sudo apt-get install adminer
or you can also download the latest version from adminer.org
A "program" can be as simple as a "set of instructions" to implement a logic.
It can be part of an "application", "component", "service" or another "program".
Application is a possibly a collection of coordinating program instances to solve a user's purpose.
Import
import android.net.Uri;
Intent openURL = new Intent(android.content.Intent.ACTION_VIEW);
openURL.setData(Uri.parse("http://www.example.com"));
startActivity(openURL);
or it can be done using,
TextView textView = (TextView)findViewById(R.id.yourID);
textView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://www.typeyourURL.com"));
startActivity(intent);
} });
You are probably printing from a signed char array. Either print from an unsigned char array or mask the value with 0xff: e.g. ar[i] & 0xFF. The c0 values are being sign extended because the high (sign) bit is set.
.h
) not for source files ( i.e., .cpp
). LinearNode.h:
#ifndef LINEARNODE_H
#define LINEARNODE_H
class LinearNode
{
// .....
};
#endif
LinearNode.cpp:
#include "LinearNode.h"
#include <iostream>
using namespace std;
// And now the definitions
LinkedList.h:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
class LinearNode; // Forward Declaration
class LinkedList
{
// ...
};
#endif
LinkedList.cpp
#include "LinearNode.h"
#include "LinkedList.h"
#include <iostream>
using namespace std;
// Definitions
test.cpp is source file is fine. Note that header files are never compiled. Assuming all the files are in a single folder -
g++ LinearNode.cpp LinkedList.cpp test.cpp -o exe.out
Non-matched part of the URL is exposed as a request attribute named HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE
:
@RequestMapping("/{id}/**")
public void foo(@PathVariable("id") int id, HttpServletRequest request) {
String restOfTheUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
...
}
It looks like psexec -h
is the way to do this:
-h If the target system is Windows Vista or higher, has the process
run with the account's elevated token, if available.
Which... doesn't seem to be listed in the online documentation in Sysinternals - PsExec.
But it works on my machine.
There is no standard C (or C++) way to enumerate files in a directory.
Under Windows you can use the FindFirstFile/FindNextFile functions to enumerate all entries in a directory. Under Linux/OSX use the opendir/readdir/closedir functions.
Approach: 1
Given original string
format: 2019/03/04 00:08:48
you can use
updated_df = df['timestamp'].astype('datetime64[ns]')
The result will be in this datetime
format: 2019-03-04 00:08:48
Approach: 2
updated_df = df.astype({'timestamp':'datetime64[ns]'})
For others who'd like to debug the two JSON objects (usually, there is a reference and a target), here is a solution you may use. It will list the "path" of different/mismatched ones from target to the reference.
level
option is used for selecting how deep you would like to look into.
show_variables
option can be turned on to show the relevant variable.
def compareJson(example_json, target_json, level=-1, show_variables=False):
_different_variables = _parseJSON(example_json, target_json, level=level, show_variables=show_variables)
return len(_different_variables) == 0, _different_variables
def _parseJSON(reference, target, path=[], level=-1, show_variables=False):
if level > 0 and len(path) == level:
return []
_different_variables = list()
# the case that the inputs is a dict (i.e. json dict)
if isinstance(reference, dict):
for _key in reference:
_path = path+[_key]
try:
_different_variables += _parseJSON(reference[_key], target[_key], _path, level, show_variables)
except KeyError:
_record = ''.join(['[%s]'%str(p) for p in _path])
if show_variables:
_record += ': %s <--> MISSING!!'%str(reference[_key])
_different_variables.append(_record)
# the case that the inputs is a list/tuple
elif isinstance(reference, list) or isinstance(reference, tuple):
for index, v in enumerate(reference):
_path = path+[index]
try:
_target_v = target[index]
_different_variables += _parseJSON(v, _target_v, _path, level, show_variables)
except IndexError:
_record = ''.join(['[%s]'%str(p) for p in _path])
if show_variables:
_record += ': %s <--> MISSING!!'%str(v)
_different_variables.append(_record)
# the actual comparison about the value, if they are not the same, record it
elif reference != target:
_record = ''.join(['[%s]'%str(p) for p in path])
if show_variables:
_record += ': %s <--> %s'%(str(reference), str(target))
_different_variables.append(_record)
return _different_variables
In 2018, you can program the "usual" style using async
and await
in Node.js.
Below is an example, that wraps request callback in a promise and then uses await
to get the resolved value.
const request = require('request');
// wrap a request in an promise
function downloadPage(url) {
return new Promise((resolve, reject) => {
request(url, (error, response, body) => {
if (error) reject(error);
if (response.statusCode != 200) {
reject('Invalid status code <' + response.statusCode + '>');
}
resolve(body);
});
});
}
// now to program the "usual" way
// all you need to do is use async functions and await
// for functions returning promises
async function myBackEndLogic() {
try {
const html = await downloadPage('https://microsoft.com')
console.log('SHOULD WORK:');
console.log(html);
// try downloading an invalid url
await downloadPage('http:// .com')
} catch (error) {
console.error('ERROR:');
console.error(error);
}
}
// run your async function
myBackEndLogic();
The old version of jQuery Cookie has been deprecated, so if you're getting the error:
$.cookie is not a function
you should upgrade to the new version.
The API for the new version is also different - rather than using
$.cookie("yourCookieName");
you should use
Cookies.get("yourCookieName");
I may be late but still...
This answer is based on removing and adding views dynamically
To disable scrolling:
View child = scoll.getChildAt(0);// since scrollView can only have one direct child
ViewGroup parent = (ViewGroup) scroll.getParent();
scroll.removeView(child); // remove child from scrollview
parent.addView(child,parent.indexOfChild(scroll));// add scroll child at the position of scrollview
parent.removeView(scroll);// remove scrollView from parent
To enable ScrollView just reverse the process
I used to work with Klassmaster in my previous company and it works really well and can integrate pretty good with build systems (maven support is excellent). But it's not free though.
Php has an function to count the occurrences in the array http://www.php.net/manual/en/function.array-count-values.php
In cases where you have multiple directives on a single DOM element and where the
order in which they’re applied matters, you can use the priority
property to order their
application. Higher numbers run first. The default priority is 0 if you don’t specify one.
EDIT: after the discussion, here's the complete working solution. The key was to remove the attribute: element.removeAttr("common-things");
, and also element.removeAttr("data-common-things");
(in case users specify data-common-things
in the html)
angular.module('app')
.directive('commonThings', function ($compile) {
return {
restrict: 'A',
replace: false,
terminal: true, //this setting is important, see explanation below
priority: 1000, //this setting is important, see explanation below
compile: function compile(element, attrs) {
element.attr('tooltip', '{{dt()}}');
element.attr('tooltip-placement', 'bottom');
element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controller) {
$compile(iElement)(scope);
}
};
}
};
});
Working plunker is available at: http://plnkr.co/edit/Q13bUt?p=preview
Or:
angular.module('app')
.directive('commonThings', function ($compile) {
return {
restrict: 'A',
replace: false,
terminal: true,
priority: 1000,
link: function link(scope,element, attrs) {
element.attr('tooltip', '{{dt()}}');
element.attr('tooltip-placement', 'bottom');
element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html
$compile(element)(scope);
}
};
});
Explanation why we have to set terminal: true
and priority: 1000
(a high number):
When the DOM is ready, angular walks the DOM to identify all registered directives and compile the directives one by one based on priority
if these directives are on the same element. We set our custom directive's priority to a high number to ensure that it will be compiled first and with terminal: true
, the other directives will be skipped after this directive is compiled.
When our custom directive is compiled, it will modify the element by adding directives and removing itself and use $compile service to compile all the directives (including those that were skipped).
If we don't set terminal:true
and priority: 1000
, there is a chance that some directives are compiled before our custom directive. And when our custom directive uses $compile to compile the element => compile again the already compiled directives. This will cause unpredictable behavior especially if the directives compiled before our custom directive have already transformed the DOM.
For more information about priority and terminal, check out How to understand the `terminal` of directive?
An example of a directive that also modifies the template is ng-repeat
(priority = 1000), when ng-repeat
is compiled, ng-repeat
make copies of the template element before other directives get applied.
Thanks to @Izhaki's comment, here is the reference to ngRepeat
source code: https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js
for example:
$_SERVER['SERVER_ADDR']
when your on IIS, try:
$_SERVER['LOCAL_ADDR']
You can also set the 'dashed' option when setting your terminal, for instance:
set term pdf dashed
Suppose a 9800GT GPU:
https://www.tutorialspoint.com/cuda/cuda_threads.htm
A block cannot have more active threads than 512 therefore __syncthreads
can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:
func1();
__syncthreads();
func2();
__syncthreads();
then the kernel must run twice and the order of execution will be:
Note:
The main point is __syncthreads
is a block-wide operation and it does not synchronize all threads.
I'm not sure about the exact number of threads that __syncthreads
can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.
Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads
.
I would greatly appreciate if someone test this again for a more accurate piece of information.
I ended up here because I was trying to conditionally add header parameters in Swagger UI, based on my own [Authentication]
attribute I added to my API method. Following the hint that @Corcus listed in a comment, I was able to derive my solution, and hopefully it will help others.
Using Reflection, it's checking if the method nested down in apiDescription
has the desired attribute (MyApiKeyAuthenticationAttribute, in my case). If it does, I can append my desired header parameters.
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) {
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
var attributes = ((System.Web.Http.Controllers.ReflectedHttpActionDescriptor)
((apiDescription.ActionDescriptor).ActionBinding.ActionDescriptor)).MethodInfo
.GetCustomAttributes(false);
if(attributes != null && attributes.Any()) {
if(attributes.Where(x => x.GetType()
== typeof(MyApiKeyAuthenticationAttribute)).Any()) {
operation.parameters.Add(new Parameter {
name = "MyApiKey",
@in = "header",
type = "string",
description = "My API Key",
required = true
});
operation.parameters.Add(new Parameter {
name = "EID",
@in = "header",
type = "string",
description = "Employee ID",
required = true
});
}
}
}
Also you can use HRTime package. It has a class StopWatch.
IF you are looking for the full path information of your executable, the reliable way to do it is to use the following:
var executable = System.Diagnostics.Process.GetCurrentProcess().MainModule
.FileName.Replace(".vshost", "");
This eliminates any issues with intermediary dlls, vshost, etc.
With the new App Launcher YOUR APPS (not chrome extensions) stored in Users/[yourusername]/Applications/Chrome Apps/
Listen the change
event.
document.querySelector("input")
.addEventListener('change', (e) => {
console.log(e.currentTarget.value);
});
It looks like you have a typo on your array, it should read:
int my_array[3][3] = {...
You don't have the _
or the {
.
Also my_array[3][3]
is an invalid location. Since computers begin counting at 0
, you are accessing position 4
. (Arrays are weird like that).
If you want just the last element:
printf("%d\n", my_array[2][2]);
If you want the entire array:
for(int i = 0; i < my_array.length; i++) {
for(int j = 0; j < my_array[i].length; j++)
printf("%d ", my_array[i][j]);
printf("\n");
}
As @Quartz mentioned, you can do something like
stage('Tests') {
parallel(
'Unit Tests': {
container('node') {
sh("npm test --cat=unit")
}
},
'API Tests': {
container('node') {
sh("npm test --cat=acceptance")
}
}
)
}
I used the following property which works fine for me:
$('#selector').dialog({
minHeight: 'auto'
});
This XML file does not appear to have any style information associated with it. The document tree is shown below.
You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml
instead of text/html
and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.
In case of JSF/Facelets files which have the default extension of .xhtml
, that can in turn happen if the HTTP request hasn't invoked the FacesServlet
and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml
file extension which is in your Firefox configuration apparently by default interpreted as text/xml
.
You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern>
of the FacesServlet
as registered in webapp's web.xml
, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf
, then you need to open the page by /some.jsf
instead of /some.xhtml
. Alternatively, you can also just change the <url-pattern>
to *.xhtml
. This way you never need to fiddle with virtual URLs.
Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.