distcc can also be used to distribute compiles not only on the current machine, but also on other machines in a farm that have distcc installed.
You probably need to update the remote URL since github puts your username in it. You can take a look at the original URL by typing
git config --get remote.origin.url
Or just go to the repository page on Github and get the new URL. Then use
git remote set-url origin https://{new url with username replaced}
to update the URL with your new username.
I finally was able to run datepicker directive in angular js , here are pointers
include following JS in order
I added the following
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"> </script>
in html code
<body ng-app="myApp" ng-controller="myController">
// some other html code
<input type="text" ng-model="date" mydatepicker />
<br/>
{{ date }}
//some other html code
</body>
in the js , make sure you code for the directive first and after that add the code for controller , else it will cause issues.
date picker directive :
var app = angular.module('myApp',[]);
app.directive('mydatepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
element.datepicker({
dateFormat: 'DD, d MM, yy',
onSelect: function (date) {
scope.date = date;
scope.$apply();
}
});
}
};
});
directive code referred from above answers.
After this directive , write the controller
app.controller('myController',function($scope){
//controller code
};
TRY THIS INSTEAD in angular js
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
along with jquery.js and jquery-ui.js
we can implement angular js datepicker as
<input type="date" ng-model="date" name="DOB">
This gives the built in datepicker and date is set in ng-model and can be used for further processing and validation.
Found this after lot of successful headbanging with previous approach. :)
use the below command to set the port number in node process while running node JS programme:
set PORT =3000 && node file_name.js
The set port can be accessed in the code as
process.env.PORT
This is works for me on Ubuntu 18.04 with Postman v7.1.1 which is released on 20 May, 2019.
Download the latest version of Postman.
Most probably your downloaded file should be in Downloads folder.
# Postman-linux-x64-7.1.1.tar.gz is my downloaded file
cd /home/YOUR_USERNAME/Downloads/
tar -xzf Postman-linux-x64-7.1.1.tar.gz Postman/
sudo mv Postman /usr/share/postman
sudo ln -s /usr/share/postman/Postman /usr/bin/postman
If you get an error like this,
/usr/share/postman/Postman: error while loading shared libraries: libgconf-2.so.4: cannot open shared object file: No such file or directory
please install libgconf-2-4.
sudo apt install libgconf-2-4
Just type postman
in your terminal and hit enter to run latest version of Postman. Now we have to create an Unity desktop file for your launcher. For create postman.desktop
file run the below command.
sudo nano ~/.local/share/applications/postman.desktop
Then paste below lines into the postman.desktop
file.
[Desktop Entry]
Encoding=UTF-8
Name=Postman
Exec=postman
Icon=/usr/share/postman/app/resources/app/assets/icon.png
Terminal=false
Type=Application
Categories=Development;
Now you can see the "Postman" icon in your Unity launcher. If you miss any point please go through this video or comment below.
I ran into the same problem as well. My problem was, that I accidentally installed the wrong connector version. Delete your currently installed version from your file system (my path looks like this: C:\Program Files\Python36\Lib\site-packages) and then execute "pip install mysql-connector-python". This should solve your problem
In AWK columns are called fields, hence NF is the key
all rows:
awk -F '<column separator>' '{print $(NF-2)}' <filename>
first row only:
awk -F '<column separator>' 'NR<=1{print $(NF-2)}' <filename>
The Wikipedia newline article might help you out. Here is an excerpt:
The different newline conventions often cause text files that have been transferred between systems of different types to be displayed incorrectly. For example, files originating on Unix or Apple Macintosh systems may appear as a single long line on some programs running on Microsoft Windows. Conversely, when viewing a file originating from a Windows computer on a Unix system, the extra CR may be displayed as ^M or at the end of each line or as a second line break.
Here is an example where pointer to data members could be useful:
#include <iostream>
#include <list>
#include <string>
template <typename Container, typename T, typename DataPtr>
typename Container::value_type searchByDataMember (const Container& container, const T& t, DataPtr ptr) {
for (const typename Container::value_type& x : container) {
if (x->*ptr == t)
return x;
}
return typename Container::value_type{};
}
struct Object {
int ID, value;
std::string name;
Object (int i, int v, const std::string& n) : ID(i), value(v), name(n) {}
};
std::list<Object*> objects { new Object(5,6,"Sam"), new Object(11,7,"Mark"), new Object(9,12,"Rob"),
new Object(2,11,"Tom"), new Object(15,16,"John") };
int main() {
const Object* object = searchByDataMember (objects, 11, &Object::value);
std::cout << object->name << '\n'; // Tom
}
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int[] numbers=new int[5];
String x=null;
System.out.print("enter the number 10:"+"/n");
for(int i=0;i<5;i++){
numbers[i] = input.nextInt();
}
System.out.print("Numbers : count"+"\n");
int count=1;
Arrays.sort(numbers);
for(int z=0;z<5;z++){
for(int j=0;j<z;j++){
if(numbers[z]==numbers[j] & j!=z){
count=count+1;
}
}
System.out.print(numbers[z]+" - "+count+"\n");
count=1;
}
You should either create a FOREIGN KEY
with ON DELETE CASCADE
:
ALTER TABLE usersmessages
ADD CONSTRAINT fk_usermessages_messageid
FOREIGN KEY (messageid)
REFERENCES messages (messageid)
ON DELETE CASCADE
, or do it using two queries in a transaction:
START TRANSACTION;;
DELETE
FROM usermessages
WHERE messageid = 1
DELETE
FROM messages
WHERE messageid = 1;
COMMIT;
Transaction affects only InnoDB
tables, though.
If you want to script all table rows then Go with Generate Scripts as described by Daniel Vassallo. You can’t go wrong here
Else Use third party tools such as ApexSQL Script or SSMS Toolpack for more advanced scripting that includes some preprocessing, selective scripting and more.
I get authenticated user by HttpServletRequest.getUserPrincipal();
Example:
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.support.RequestContext;
import foo.Form;
@Controller
@RequestMapping(value="/welcome")
public class IndexController {
@RequestMapping(method=RequestMethod.GET)
public String getCreateForm(Model model, HttpServletRequest request) {
if(request.getUserPrincipal() != null) {
String loginName = request.getUserPrincipal().getName();
System.out.println("loginName : " + loginName );
}
model.addAttribute("form", new Form());
return "welcome";
}
}
just use onkeypress event like below:
<input type="text" name="onlyalphabet" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
I wrote a simple class to build a confusion matrix without the need to depend on a machine learning library.
The class can be used such as:
labels = ["cat", "dog", "velociraptor", "kraken", "pony"]
confusionMatrix = ConfusionMatrix(labels)
confusionMatrix.update("cat", "cat")
confusionMatrix.update("cat", "dog")
...
confusionMatrix.update("kraken", "velociraptor")
confusionMatrix.update("velociraptor", "velociraptor")
confusionMatrix.plot()
The class ConfusionMatrix:
import pylab
import collections
import numpy as np
class ConfusionMatrix:
def __init__(self, labels):
self.labels = labels
self.confusion_dictionary = self.build_confusion_dictionary(labels)
def update(self, predicted_label, expected_label):
self.confusion_dictionary[expected_label][predicted_label] += 1
def build_confusion_dictionary(self, label_set):
expected_labels = collections.OrderedDict()
for expected_label in label_set:
expected_labels[expected_label] = collections.OrderedDict()
for predicted_label in label_set:
expected_labels[expected_label][predicted_label] = 0.0
return expected_labels
def convert_to_matrix(self, dictionary):
length = len(dictionary)
confusion_dictionary = np.zeros((length, length))
i = 0
for row in dictionary:
j = 0
for column in dictionary:
confusion_dictionary[i][j] = dictionary[row][column]
j += 1
i += 1
return confusion_dictionary
def get_confusion_matrix(self):
matrix = self.convert_to_matrix(self.confusion_dictionary)
return self.normalize(matrix)
def normalize(self, matrix):
amin = np.amin(matrix)
amax = np.amax(matrix)
return [[(((y - amin) * (1 - 0)) / (amax - amin)) for y in x] for x in matrix]
def plot(self):
matrix = self.get_confusion_matrix()
pylab.figure()
pylab.imshow(matrix, interpolation='nearest', cmap=pylab.cm.jet)
pylab.title("Confusion Matrix")
for i, vi in enumerate(matrix):
for j, vj in enumerate(vi):
pylab.text(j, i+.1, "%.1f" % vj, fontsize=12)
pylab.colorbar()
classes = np.arange(len(self.labels))
pylab.xticks(classes, self.labels)
pylab.yticks(classes, self.labels)
pylab.ylabel('Expected label')
pylab.xlabel('Predicted label')
pylab.show()
What about something like this, without a button:
<input type="text" placeholder="Search..." [value]="searchValue" onblur="this.value=''">
Bytes are transparently converted to ints.
Just say
int i= rno[0];
We can update GTF answer to update timestamps easily
$data = array(
array(
'name'=>'Coder 1', 'rep'=>'4096',
'created_at'=>date('Y-m-d H:i:s'),
'modified_at'=> date('Y-m-d H:i:s')
),
array(
'name'=>'Coder 2', 'rep'=>'2048',
'created_at'=>date('Y-m-d H:i:s'),
'modified_at'=> date('Y-m-d H:i:s')
),
//...
);
Coder::insert($data);
Update: to simplify the date we can use carbon as @Pedro Moreira suggested
$now = Carbon::now('utc')->toDateTimeString();
$data = array(
array(
'name'=>'Coder 1', 'rep'=>'4096',
'created_at'=> $now,
'modified_at'=> $now
),
array(
'name'=>'Coder 2', 'rep'=>'2048',
'created_at'=> $now,
'modified_at'=> $now
),
//...
);
Coder::insert($data);
UPDATE2: for laravel 5 , use updated_at
instead of modified_at
$now = Carbon::now('utc')->toDateTimeString();
$data = array(
array(
'name'=>'Coder 1', 'rep'=>'4096',
'created_at'=> $now,
'updated_at'=> $now
),
array(
'name'=>'Coder 2', 'rep'=>'2048',
'created_at'=> $now,
'updated_at'=> $now
),
//...
);
Coder::insert($data);
var UTF8ToBin=function(f){for(var a,c=0,d=(f=unescape(encodeURIComponent(f))).length,b="";c<d;c++){for(a=f.charCodeAt(c).toString(2);a.length%8!=0;){a="0"+a}b+=a}return b},binToUTF8=function(f){for(var a,c=0,d=f.length,b="";c<d;c+=8){b+="%"+((a=parseInt(f.substr(c,8),2).toString(16)).length%2==0?a:"0"+a)}return decodeURIComponent(b)};
This is a small minified JavaScript Code to convert UTF8 to Binary and Vice versa.
Adding label tags around the radio buttons using regular HTML will fix the 'labelfor' issue as well:
<label><%= Html.RadioButton("blah", !Model.blah) %> Yes</label>
<label><%= Html.RadioButton("blah", Model.blah) %> No</label>
Clicking on the text now selects the appropriate radio button.
You can use git cherry-pick for this. 'cherry-pick' will apply a commit onto the branch your on now.
then do
git rebase --hard <SHA1 of A>
then apply the D and E commits.
git cherry-pick <SHA1 of D>
git cherry-pick <SHA1 of E>
This will skip out the B and C commit. Having said that it might be impossible to apply the D commit to the branch without B, so YMMV.
public table2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 485, 218);
setTitle("jtable");
getContentPane().setLayout(null);
String data[][] = { { "Row1/1", "Row1/2", "Row1/3" },
{ "Row2/1", "Row2/2", "Row2/3" },
{ "Row3/1", "Row3/2", "Row3/3" },
{ "Row4/1", "Row4/2", "Row4/3" }, };
String header[] = { "Column 1", "Column 2", "Column 3" };
// Table
JTable table = new JTable(data,header);
// ScrollPane
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(36, 37, 407, 79);
getContentPane().add(scrollPane);
}
}
try this!!
I used this function htmlspecialchars for alt attributes in images
This was the easiest for me on a Windows Server: In VisualSVN right-click your repository, then select Properties... and then the Hooks tab.
Select Pre-revision property change hook, click Edit.
I needed to be able to change the Author - it often happens on remote computers used by multiple people, that by mistake we check-in using someone else's stored credentials.
Here is the modified community wiki script to paste:
@ECHO OFF
:: Set all parameters. Even though most are not used, in case you want to add
:: changes that allow, for example, editing of the author or addition of log messages.
set repository=%1
set revision=%2
set userName=%3
set propertyName=%4
set action=%5
:: Only allow the author to be changed, but not message ("svn:log"), etc.
if /I not "%propertyName%" == "svn:author" goto ERROR_PROPNAME
:: Only allow modification of a log message, not addition or deletion.
if /I not "%action%" == "M" goto ERROR_ACTION
:: Make sure that the new svn:log message is not empty.
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if "%bIsEmpty%" == "true" goto ERROR_EMPTY
goto :eof
:ERROR_EMPTY
echo Empty svn:author messages are not allowed. >&2
goto ERROR_EXIT
:ERROR_PROPNAME
echo Only changes to svn:author messages are allowed. >&2
goto ERROR_EXIT
:ERROR_ACTION
echo Only modifications to svn:author revision properties are allowed. >&2
goto ERROR_EXIT
:ERROR_EXIT
exit /b 1
It depends on what environment you're running in. In a web browser you simply need to make sure that file1.js
is loaded before file2.js
:
<script src="file1.js"></script>
<script src="file2.js"></script>
In node.js, the recommended way is to make file1 a module then you can load it with the require
function:
require('path/to/file1.js');
It's also possible to use node's module style in HTML using the require.js library.
You should have enough space for array1
array and use something like strcat
to contact array1
to array2
:
char array1[BIG_ENOUGH];
char array2[X];
/* ...... */
/* check array bounds */
/* ...... */
strcat(array1, array2);
To delete all Docker local Docker images follow 2 steps ::
step 1 : docker images ( list all docker images with ids )
example :
REPOSITORY TAG IMAGE ID CREATED SIZE
pradip564/my latest 31e522c6cfe4 3 months ago 915MB
step 2 : docker image rm 31e522c6cfe4 ( IMAGE ID)
OUTPUT : image deleted
example:
import java.util.*;
import java.lang.Object;
import java.text.Collator;
public class CurrentTime{
public class CurrentTime
{
public static void main( String[] args )
{
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get( Calendar.HOUR );
int minute = calendar.get( Calendar.MINUTE );
// int second = calendar.get(Calendar.SECOND);
if( calendar.get( Calendar.AM_PM ) == 0 ){
am_pm = "AM";
if(hour >=10)
System.out.println( "welcome" );
}
else{
am_pm = "PM";
if(hour<6)
System.out.println( "welcome" );
}
String time = "Current Time : " + hour + ":" + minute + " " + am_pm;
System.out.println( time );
}
}
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
This can be addressed simple by CSS attribute:
XML:
<label name="pageTac"> Hello how are you doing?
Thank you I'm Good</label>
CSS
.pageText{
white-space:pre !important; // this wraps the xml text.}
HTML / XSL
<tr>
<td class="pageText"><xsl:value-of select="$Dictionary/infolabels/label[@name='pageTac']" />
</td></tr>
I solved the same problem by installing "matplotlib".
Check it here :
https://stackoverflow.com/a/53644664/1084987
You can create something like if condition afterwards, like
if(!contains(array, obj)) add();
Open Anaconda Prompt (base):
conda update -n base -c defaults conda
conda create -n python38 python=3.8
conda activate python38
python
You have to pass a function to expect
. Like this:
expect(model.get.bind(model, 'z')).to.throw('Property does not exist in model schema.');
expect(model.get.bind(model, 'z')).to.throw(new Error('Property does not exist in model schema.'));
The way you are doing it, you are passing to expect
the result of calling model.get('z')
. But to test whether something is thrown, you have to pass a function to expect
, which expect
will call itself. The bind
method used above creates a new function which when called will call model.get
with this
set to the value of model
and the first argument set to 'z'
.
A good explanation of bind
can be found here.
I know this is an old question but on Windows, this filters the git output to the files and changed line numbers:
(git diff -p --stat) | findstr "@@ --git"
diff --git a/dir1/dir2/file.cpp b/dir1/dir2/file.cpp
@@ -47,6 +47,7 @@ <some function name>
@@ -97,7 +98,7 @@ <another functon name>
To extract the files and the changed lines from that is a bit more work:
for /f "tokens=3,4* delims=-+ " %f in ('^(git diff -p --stat .^) ^| findstr ^"@@ --git^"') do @echo %f
a/dir1/dir2/file.cpp
47,7
98,7
You can try settings of code::block
, there is a complier..., then you select in C mode.
nohup sh -x runShellScripts.sh &
It seems pretty consistent to me; positive indices are also non-inclusive. I think you're doing it wrong. Remembering that range() is also non-inclusive, and that Python arrays are 0-indexed, here's a sample python session to illustrate:
>>> d = range(10)
>>> d
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d[9]
9
>>> d[-1]
9
>>> d[0:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> d[0:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> len(d)
10
To complete the other answers: If you are using C++11, use nullptr
, which is a keyword that means a void pointer pointing to null. (instead of NULL
, which is not a pointer type)
Solution:
Step1: Uncomment the php_curl.dll from php.ini
Step2: Copy the following three files from php installed directory.i.e "C:\\php7".
libeay32.dll,
libssh2.dll,
ssleay32.dll
Step3: Paste the files under two place
httpd.conf's ServerRoot directive. i.e "C\Apache24"
apache bin directory. i.e "C\Apache24\bin"
Step4: Restart apache.
That's all. I solve the problem by this way.Hope it might work for you.
The solution is given here. https://abcofcomputing.blogspot.com/2017/06/php7-unable-to-load-phpcurldll.html
The problem is that skew
isn't being subsetted in colour=factor(skew)
, so it's the wrong length. Since subset(skew, product == 'p1')
is the same as subset(skew, product == 'p3')
, in this case it doesn't matter which subset is used. So you can solve your problem with:
p1 <- ggplot(df, aes(x=subset(price, product=='p1'),
y=subset(price, product=='p3'),
colour=factor(subset(skew, product == 'p1')))) +
geom_point(size=2, shape=19)
Note that most R users would write this as the more concise:
p1 <- ggplot(df, aes(x=price[product=='p1'],
y=price[product=='p3'],
colour=factor(skew[product == 'p1']))) +
geom_point(size=2, shape=19)
Not working for me.
The mode is true, the file perms have been changed, but git says there's no work to do.
git init
git add dir/file
chmod 440 dir/file
git commit -a
The problem seems to be that git recognizes only certain permission changes.
Simply type conda update pandas
in your preferred shell (on Windows, use cmd; if Anaconda is not added to your PATH use the Anaconda prompt). You can of course use Eclipse together with Anaconda, but you need to specify the Python-Path (the one in the Anaconda-Directory).
See this document for a detailed instruction.
The standard tool for listing symbols is nm
, you can use it simply like this:
nm -gD yourLib.so
If you want to see symbols of a C++ library, add the "-C" option which demangle the symbols (it's far more readable demangled).
nm -gDC yourLib.so
If your .so file is in elf format, you have two options:
Either objdump
(-C
is also useful for demangling C++):
$ objdump -TC libz.so
libz.so: file format elf64-x86-64
DYNAMIC SYMBOL TABLE:
0000000000002010 l d .init 0000000000000000 .init
0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 free
0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 __errno_location
0000000000000000 w D *UND* 0000000000000000 _ITM_deregisterTMCloneTable
Or use readelf
:
$ readelf -Ws libz.so
Symbol table '.dynsym' contains 112 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND
1: 0000000000002010 0 SECTION LOCAL DEFAULT 10
2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.2.5 (14)
3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND __errno_location@GLIBC_2.2.5 (14)
4: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable
FormatDateTime(Now, DateFormat.ShortDate)
Use otool:
otool -TV your.dylib
OR
nm -g your.dylib
I was getting this problem from my Dockerfile as I had:
RUN bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)
However, according to this issue, it was solved:
The exec form makes it possible to avoid shell string munging, and to
RUN
commands using a base image that does not contain/bin/sh
.Note
To use a different shell, other than
/bin/sh
, use the exec form passing in the desired shell. For example,RUN ["/bin/bash", "-c", "echo hello"]
RUN ["/bin/bash", "-c", "bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)"]
Notice the quotes around each parameter.
Replace
data: { patientID: "1" },
with
data: "{ 'patientID': '1' }",
Further reading: 3 mistakes to avoid when using jQuery with ASP.NET
Not sure whether this answer has already appeared...
For the particular pattern in the question, you can just do it with a single grep()
call,
grep("A[169]", myfile$Letter)
var listItems= "";
var jsonData = jsonObj.d;
for (var i = 0; i < jsonData.Table.length; i++){
listItems+= "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
}
$("#<%=DLState.ClientID%>").html(listItems);
Example
<html>
<head></head>
<body>
<select id="DLState">
</select>
</body>
</html>
/*javascript*/
var jsonList = {"Table" : [{"stateid" : "2","statename" : "Tamilnadu"},
{"stateid" : "3","statename" : "Karnataka"},
{"stateid" : "4","statename" : "Andaman and Nicobar"},
{"stateid" : "5","statename" : "Andhra Pradesh"},
{"stateid" : "6","statename" : "Arunachal Pradesh"}]}
$(document).ready(function(){
var listItems= "";
for (var i = 0; i < jsonList.Table.length; i++){
listItems+= "<option value='" + jsonList.Table[i].stateid + "'>" + jsonList.Table[i].statename + "</option>";
}
$("#DLState").html(listItems);
});
If you want to determine whether a key is there in map or not, you can use the find() or count() member function of map. The find function which is used here in example returns the iterator to element or map::end otherwise. In case of count the count returns 1 if found, else it returns zero(or otherwise).
if(phone.count(key))
{ //key found
}
else
{//key not found
}
for(int i=0;i<v.size();i++){
phoneMap::iterator itr=phone.find(v[i]);//I have used a vector in this example to check through map you cal receive a value using at() e.g: map.at(key);
if(itr!=phone.end())
cout<<v[i]<<"="<<itr->second<<endl;
else
cout<<"Not found"<<endl;
}
According to the latest Apple Human Interface Guidelines:
In portrait orientation, tab bar icons appear above tab titles. In landscape orientation, the icons and titles appear side-by-side. Depending on the device and orientation, the system displays either a regular or compact tab bar. Your app should include custom tab bar icons for both sizes.
I suggest you to use the above link to understand the full concept. Because apple update it's document in regular interval
with prototype and without space :
String.prototype.trimToLength = function (trimLenght) {
return this.length > trimLenght ? this.substring(0, trimLenght - 3) + '...' : this
};
The object can be used as a parameter in Exception.with_traceback()
function:
except Exception as e:
tb = sys.exc_info()
print(e.with_traceback(tb[2]))
I know its kind of odd but I experienced this error for a c# application and finally I found out the problem is the Icon of the form! when I changed it everything just worked fine.
I should say that I had this error just in XP not in 7 or 8 .
Just a small correction to the first answer in this thread.
Even for Stack, you need to create new object with generics if you are using Stack from java util packages.
Right usage:
Stack<Integer> s = new Stack<Integer>();
Stack<String> s1 = new Stack<String>();
s.push(7);
s.push(50);
s1.push("string");
s1.push("stack");
if used otherwise, as mentioned in above post, which is:
/*
Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);
*/
Although this code works fine, has unsafe or unchecked operations which results in error.
Code for Find the Column Name same as using the Like
in sql.
foreach (DataGridViewColumn column in GrdMarkBook.Columns)
//GrdMarkBook is Data Grid name
{
string HeaderName = column.HeaderText.ToString();
// This line Used for find any Column Have Name With Exam
if (column.HeaderText.ToString().ToUpper().Contains("EXAM"))
{
int CoumnNo = column.Index;
}
}
I solved this problem with:
inputObj.css('cssText', inputObj.attr('style')+'padding-left: ' + (width + 5) + 'px !IMPORTANT;');
So no inline-Style is lost, an the last overrides the first
If you are running the .java file in Eclipse you need to add the resource path in the build path . after that you will not see this error
INSERT INTO table1
SELECT "A string", 5, idTable2
FROM table2
WHERE ...
See: http://dev.mysql.com/doc/refman/5.6/en/insert-select.html
REST is almost always going to be faster. The main advantage of SOAP is that it provides a mechanism for services to describe themselves to clients, and to advertise their existence.
REST is much more lightweight and can be implemented using almost any tool, leading to lower bandwidth and shorter learning curve. However, the clients have to know what to send and what to expect.
In general, When you're publishing an API to the outside world that is either complex or likely to change, SOAP will be more useful. Other than that, REST is usually the better option.
value = (value) ? false : true;
Seems like Android Studio (using version 3.5.1) gets into a weird state after a while. This worked for me.
File -> Invalidate Caches / Restart -> Invalidate and Restart
On Windows, installation of easy_install is a little bit trickier, but still quite easy. The easiest way to do it is to download the distribute_setup.py file and run it. The easiest way to run the file is to open your downloads folder and double-click on the file.
Next, add the easy_install command and other Python scripts to the command search path, by adding your Python installation’s Scripts folder to the PATH environment variable. To do that, right-click on the “Computer” icon on the Desktop or in the Start menu, and choose “Properties”. Then click on “Advanced System settings” (in Windows XP, click on the “Advanced” tab instead). Then click on the “Environment variables” button. Finally, double-click on the “Path” variable in the “System variables” section, and add the path of your Python interpreter’s Scripts folder. Be sure to delimit it from existing values with a semicolon. Assuming you are using Python 2.7 on the default path, add the following value:
;C:\Python27\Scripts And you are done! To check that it worked, open the Command Prompt and execute easy_install. If you have User Account Control enabled on Windows Vista or Windows 7, it should prompt you for administrator privileges.
Now that you have easy_install, you can use it to install pip:
easy_install pip
As per the official installation page of skimage (skimage Installation) : python-skimage package depends on matplotlib, scipy, pil, numpy and six.
So install them first using
sudo apt-get install python-matplotlib python-numpy python-pil python-scipy
Apparently skimage is a part of Cython which in turn is a superset of python and hence you need to install Cython to be able to use skimage.
sudo apt-get install build-essential cython
Now install skimage package using
sudo apt-get install python-skimage
This solved the Import error for me.
my problem was not including the ../ before the image name
background-image: url("../image.png");
loop { begin Bar.new rescue SystemExit p $! #: #<SystemExit: exit> end }
This will print #<SystemExit: exit>
in an infinite loop, without ever exiting.
I wanted to get only IP addresses that began with "10", from any file in a directory:
grep -o -nr "[10]\{2\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}" /var/www
Sounds like you're calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR.
e.g. This will give the error because @SQL needs to be NVARCHAR
DECLARE @SQL VARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL
So:
DECLARE @SQL NVARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL
Here is a generic example of using a weak reference and static handler class to resolve the problem (as recommended in the Lint documentation):
public class MyClass{
//static inner class doesn't hold an implicit reference to the outer class
private static class MyHandler extends Handler {
//Using a weak reference means you won't prevent garbage collection
private final WeakReference<MyClass> myClassWeakReference;
public MyHandler(MyClass myClassInstance) {
myClassWeakReference = new WeakReference<MyClass>(myClassInstance);
}
@Override
public void handleMessage(Message msg) {
MyClass myClass = myClassWeakReference.get();
if (myClass != null) {
...do work here...
}
}
}
/**
* An example getter to provide it to some external class
* or just use 'new MyHandler(this)' if you are using it internally.
* If you only use it internally you might even want it as final member:
* private final MyHandler mHandler = new MyHandler(this);
*/
public Handler getHandler() {
return new MyHandler(this);
}
}
Like this:
>>> structTime = time.localtime()
>>> datetime.datetime(*structTime[:6])
datetime.datetime(2009, 11, 8, 20, 32, 35)
You can refresh the Python shell by pressing f5, or go to Run-> Run Module. This way you don't have to change the directory to read something from the file. Python will automatically change the directory. But if you want to work with different files from different directory in the Python Shell, then you can change the directory in sys, as Cameron said earlier.
Please consider the follwing codes:
from numpy import zeros
scores = zeros((len(chain1),len(chain2)), float)
NOTE:
line
someButton.setTitle("New Title", forState: .normal)
works only when Title type is Plain.
If you have no FIRST/FIRST conflicts and no FIRST/FOLLOW conflicts, your grammar is LL(1).
An example of a FIRST/FIRST conflict:
S -> Xb | Yc
X -> a
Y -> a
By seeing only the first input symbol a, you cannot know whether to apply the production S -> Xb or S -> Yc, because a is in the FIRST set of both X and Y.
An example of a FIRST/FOLLOW conflict:
S -> AB
A -> fe | epsilon
B -> fg
By seeing only the first input symbol f, you cannot decide whether to apply the production A -> fe or A -> epsilon, because f is in both the FIRST set of A and the FOLLOW set of A (A can be parsed as epsilon and B as f).
Notice that if you have no epsilon-productions you cannot have a FIRST/FOLLOW conflict.
If the user is interacting with another application, it may not be possible to bring yours to the front. As a general rule, a process can only expect to set the foreground window if that process is already the foreground process. (Microsoft documents the restrictions in the SetForegroundWindow() MSDN entry.) This is because:
foreach($array as $item=>$values){
echo $values->filepath;
}
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
kieron's answer contains w3schools ref. to which nobody rely , bobince's answer gives link , which actually tells native implementation of IE ,
so here is the original documentation quoted to rightly understand what readystate represents :
The XMLHttpRequest object can be in several states. The readyState attribute must return the current state, which must be one of the following values:
UNSENT (numeric value 0)
The object has been constructed.OPENED (numeric value 1)
The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.LOADING (numeric value 3)
The response entity body is being received.DONE (numeric value 4)
The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).
Please Read here : W3C Explaination Of ReadyState
You can use the tag canvas
and "draw" the background, which work on IE9, Gecko and Webkit.
For arbitrary SQL, use jOOQ. jOOQ currently supports SELECT
, INSERT
, UPDATE
, DELETE
, TRUNCATE
, and MERGE
. You can create SQL like this:
String sql1 = DSL.using(SQLDialect.MYSQL)
.select(A, B, C)
.from(MY_TABLE)
.where(A.equal(5))
.and(B.greaterThan(8))
.getSQL();
String sql2 = DSL.using(SQLDialect.MYSQL)
.insertInto(MY_TABLE)
.values(A, 1)
.values(B, 2)
.getSQL();
String sql3 = DSL.using(SQLDialect.MYSQL)
.update(MY_TABLE)
.set(A, 1)
.set(B, 2)
.where(C.greaterThan(5))
.getSQL();
Instead of obtaining the SQL string, you could also just execute it, using jOOQ. See
(Disclaimer: I work for the company behind jOOQ)
I was able to get past this by using the Array keyword instead of empty brackets:
const enhancers: Array<any> = [];
Use:
if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension())
}
If you want to upload file using AJAX here is code which you can use for file uploading.
$(document).ready(function() {
var options = {
beforeSubmit: showRequest,
success: showResponse,
dataType: 'json'
};
$('body').delegate('#image','change', function(){
$('#upload').ajaxForm(options).submit();
});
});
function showRequest(formData, jqForm, options) {
$("#validation-errors").hide().empty();
$("#output").css('display','none');
return true;
}
function showResponse(response, statusText, xhr, $form) {
if(response.success == false)
{
var arr = response.errors;
$.each(arr, function(index, value)
{
if (value.length != 0)
{
$("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>');
}
});
$("#validation-errors").show();
} else {
$("#output").html("<img src='"+response.file+"' />");
$("#output").css('display','block');
}
}
Here is the HTML for Upload the file
<form class="form-horizontal" id="upload" enctype="multipart/form-data" method="post" action="upload/image'" autocomplete="off">
<input type="file" name="image" id="image" />
</form>
Okay. I finally got to the bottom of this. You need to jump through some hoops to get the PUT and DELETE verbs working correctly with IIS8. In fact if you install the release candidate of VS 2012 and create a new WEB API project you'll find that the sample PUT and DELETE methods return 404 errors out of the box.
To use the PUT and DELETE verbs with the Web API you need to edit %userprofile%\documents\iisexpress\config\applicationhost.config and add the verbs to the ExtensionlessUrl handler as follows:
Change this line:
<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
to:
<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
In addition to the above you should ensure WebDAV is not interfering with your requests. This can be done by commenting out the following lines from applicationhost.config.
<add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" />
<add name="WebDAVModule" />
<add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" />
Also be aware that the default Web API convention is that your method name should be the same as the invoked HTTP verb. For example if you're sending an HTTP delete request your method, by default, should be named Delete.
This Link might be helpful for you.
Every time I've wanted a sleep in the middle of my function, I refactored to use a setTimeout().
Matthew Brindley, your code worked very good for some website I needed (with login), but I needed to change to HttpWebRequest
and HttpWebResponse
otherwise I get a 404 Bad Request from the remote server. Also I would like to share my workaround using your code, and is that I tried it to login to a website based on moodle, but it didn't work at your step "GETting the page behind the login form" because when successfully POSTing the login, the Header 'Set-Cookie'
didn't return anything despite other websites does.
So I think this where we need to store cookies for next Requests, so I added this.
To the "POSTing to the login form" code block :
var cookies = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
req.CookieContainer = cookies;
And To the "GETting the page behind the login form" :
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(resp.Cookies);
getRequest.Headers.Add("Cookie", cookieHeader);
Doing this, lets me Log me in and get the source code of the "page behind login" (website based moodle) I know this is a vague use of the CookieContainer
and HTTPCookies because we may ask first is there a previously set of cookies saved before sending the request to the server. This works without problem anyway, but here's a good info to read about WebRequest
and WebResponse
with sample projects and tutorial:
Retrieving HTTP content in .NET
How to use HttpWebRequest and HttpWebResponse in .NET
this solution work only .if your want to ignore this Warning
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="GoogleAppIndexingWarning"
package="com.example.saloononlinesolution">
You can set href
attribute to javascript:void(0)
.disabled {_x000D_
/* Disabled link style */_x000D_
color: black;_x000D_
}
_x000D_
<a class="disabled" href="javascript:void(0)">LINK</a>
_x000D_
I found that calling git is rather slow (any of the subcommands), especially for updating the prompt. Time varies between .1 and .2 seconds within the root dir of a repo, and over .2 seconds outside a repo, on a top notch machine (raid 1, 8 gb ram, 8 hardware threads). It does run Cygwin, though.
Therefore I wrote this script for speed:
#!/usr/bin/perl
$cwd=$ENV{PWD}; #`pwd`;
chomp $cwd;
while (length $cwd)
{
-d "$cwd/.git" and do {
-f "$cwd/.git/HEAD" and do {
open IN, "<", "$cwd/.git/HEAD";
$_=<IN>;
close IN;
s@ref: refs/heads/@@;
print $_;
};
exit;
};
$cwd=~s@/[^/]*$@@;
}
May need some tweaking.
Executive summary:
int a[17];
size_t n = sizeof(a)/sizeof(a[0]);
Full answer:
To determine the size of your array in bytes, you can use the sizeof
operator:
int a[17];
size_t n = sizeof(a);
On my computer, ints are 4 bytes long, so n is 68.
To determine the number of elements in the array, we can divide the total size of the array by the size of the array element. You could do this with the type, like this:
int a[17];
size_t n = sizeof(a) / sizeof(int);
and get the proper answer (68 / 4 = 17), but if the type of
a
changed you would have a nasty bug if you forgot to change
the sizeof(int)
as well.
So the preferred divisor is sizeof(a[0])
or the equivalent sizeof(*a)
, the size of the first element of the array.
int a[17];
size_t n = sizeof(a) / sizeof(a[0]);
Another advantage is that you can now easily parameterize the array name in a macro and get:
#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
int a[17];
size_t n = NELEMS(a);
As others have said, it's macro recording, and you turn it off with q. Here's a nice article about how-to and why it's useful.
You can enter these module class suffixes for any module to better control where it will show or be hidden.
.visible-phone
.visible-tablet
.visible-desktop
.hidden-phone
.hidden-tablet
.hidden-desktop
http://twitter.github.com/bootstrap/scaffolding.html scroll to bottom
You need to call the AddAddress
method once for every recipient. Like so:
$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..
Better yet, add them as Carbon Copy recipients.
$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..
To make things easy, you should loop through an array to do this.
$recipients = array(
'[email protected]' => 'Person One',
'[email protected]' => 'Person Two',
// ..
);
foreach($recipients as $email => $name)
{
$mail->AddCC($email, $name);
}
First, see if you have splitunc()
as an available function within os.path
. The first item returned should be what you want... but I am on Linux and I do not have this function when I import os
and try to use it.
Otherwise, one semi-ugly way that gets the job done is to use:
>>> pathname = "\\C:\\mystuff\\project\\file.py"
>>> pathname
'\\C:\\mystuff\\project\\file.py'
>>> print pathname
\C:\mystuff\project\file.py
>>> "\\".join(pathname.split('\\')[:-2])
'\\C:\\mystuff'
>>> "\\".join(pathname.split('\\')[:-1])
'\\C:\\mystuff\\project'
which shows retrieving the directory just above the file, and the directory just above that.
Set Your Own application Path
Dim myPathsValues As String
TextBox1.Text = Application.StartupPath
TextBox2.Text = Len(Application.StartupPath)
TextBox3.Text = Microsoft.VisualBasic.Right(Application.StartupPath, 10)
myPathsValues = Val(TextBox2.Text) - 9
TextBox4.Text = Microsoft.VisualBasic.Left(Application.StartupPath, myPathsValues) & "Reports"
System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml("Red");
(Use my method if you want to accept HTML-style hex colors.)
Set width and height of the outer container
div. Then use below styling on img:
.container img{
width:100%;
height:auto;
max-height:100%;
}
This will help you to keep an aspect ratio of your img
My problem was that the nuget package manager did not do a real update but the files contained references to older versions, so i first removed all the installed mvc related packages (including razor and web api) then installed them over again and updating the version of the razor in views/web.config to version 3.0.0.
If you already have the border from shape just add elevation:
<LinearLayout
android:id="@+id/layout"
...
android:elevation="2dp"
android:background="@drawable/rectangle" />
1 - You can use the same activity as both dialog and full screen, dynamically:
Call setTheme(android.R.style.Theme_Dialog)
before calling setContentView(...)
and super.oncreate()
in your Activity.
2 - If you don't plan to change the activity theme style you can use
<activity android:theme="@android:style/Theme.Dialog" />
(as mentioned by @faisal khan)
You can do it using this class I just made. With this class you can use the Map
object like another dictionary(including json serialization) or with the dot notation. I hope help you:
class Map(dict):
"""
Example:
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
"""
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.iteritems():
self[k] = v
if kwargs:
for k, v in kwargs.iteritems():
self[k] = v
def __getattr__(self, attr):
return self.get(attr)
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __setitem__(self, key, value):
super(Map, self).__setitem__(key, value)
self.__dict__.update({key: value})
def __delattr__(self, item):
self.__delitem__(item)
def __delitem__(self, key):
super(Map, self).__delitem__(key)
del self.__dict__[key]
Usage examples:
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
# Add new key
m.new_key = 'Hello world!'
print m.new_key
print m['new_key']
# Update values
m.new_key = 'Yay!'
# Or
m['new_key'] = 'Yay!'
# Delete key
del m.new_key
# Or
del m['new_key']
here is an example, where the length of the array is changed during execution of the loop
import java.util.ArrayList;
public class VariableArrayLengthLoop {
public static void main(String[] args) {
//create new ArrayList
ArrayList<String> aListFruits = new ArrayList<String>();
//add objects to ArrayList
aListFruits.add("Apple");
aListFruits.add("Banana");
aListFruits.add("Orange");
aListFruits.add("Strawberry");
//iterate ArrayList using for loop
for(int i = 0; i < aListFruits.size(); i++){
System.out.println( aListFruits.get(i) + " i = "+i );
if ( i == 2 ) {
aListFruits.add("Pineapple");
System.out.println( "added now a Fruit to the List ");
}
}
}
}
To copy all from Local Location to Remote Location (Upload)
scp -r /path/from/destination username@hostname:/path/to/destination
To copy all from Remote Location to Local Location (Download)
scp -r username@hostname:/path/from/destination /path/to/destination
Custom Port where xxxx
is custom port number
scp -r -P xxxx username@hostname:/path/from/destination /path/to/destination
Copy on current directory from Remote to Local
scp -r username@hostname:/path/from/file .
Help:
-r
Recursively copy all directories and files/
, Get full location by pwd
scp
will replace all existing fileshostname
will be hostname or IP address-P portnumber
Note: Sometimes the custom port will not work due to the port not being allowed in the firewall, so make sure that custom port is allowed in the firewall for incoming and outgoing connection
I know this question is old, but no one has mentioned a native solution yet. If you're not trying to support archaic browsers (which you shouldn't be at this point), you can use array.filter
:
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
_x000D_
var found = arr.filter(function(item) { return item.name === 'k1'; });_x000D_
_x000D_
console.log('found', found[0]);
_x000D_
Check the console.
_x000D_
You can see a list of supported browsers here.
In the future with ES6, you'll be able to use array.find.
You can put a ^
in the beginning of a character set to match anything but those characters.
[^=]*
will match everything but =
Simply go to the directory where the troubling file is, type touch *
without quotes in the console, and you should be good.
The use of file.exists() to test for the existence of the directory is a problem in the original post. If subDir included the name of an existing file (rather than just a path), file.exists() would return TRUE, but the call to setwd() would fail because you can't set the working directory to point at a file.
I would recommend the use of file_test(op="-d", subDir), which will return "TRUE" if subDir is an existing directory, but FALSE if subDir is an existing file or a non-existent file or directory. Similarly, checking for a file can be accomplished with op="-f".
Additionally, as described in another comment, the working directory is part of the R environment and should be controlled by the user, not a script. Scripts should, ideally, not change the R environment. To address this problem, I might use options() to store a globally available directory where I wanted all of my output.
So, consider the following solution, where someUniqueTag is just a programmer-defined prefix for the option name, which makes it unlikely that an option with the same name already exists. (For instance, if you were developing a package called "filer", you might use filer.mainDir and filer.subDir).
The following code would be used to set options that are available for use later in other scripts (thus avoiding the use of setwd() in a script), and to create the folder if necessary:
mainDir = "c:/path/to/main/dir"
subDir = "outputDirectory"
options(someUniqueTag.mainDir = mainDir)
options(someUniqueTag.subDir = "subDir")
if (!file_test("-d", file.path(mainDir, subDir)){
if(file_test("-f", file.path(mainDir, subDir)) {
stop("Path can't be created because a file with that name already exists.")
} else {
dir.create(file.path(mainDir, subDir))
}
}
Then, in any subsequent script that needed to manipulate a file in subDir, you might use something like:
mainDir = getOption(someUniqueTag.mainDir)
subDir = getOption(someUniqueTag.subDir)
filename = "fileToBeCreated.txt"
file.create(file.path(mainDir, subDir, filename))
This solution leaves the working directory under the control of the user.
many times i have noticed that site wit shared hosting do not allow to change settings in php.ini files. one also can not even crate .htaaccess file at all. in such situation one can try following things
ini_set('upload_max_filesize', '10M');
ini_set('post_max_size', '10M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);
This code just works perfectly for bootstrap 4. The problem in other codes were how the modal-backdrop is selected. It'll be better if you used the jQuery next select on the actual modal after the modal has been shown.
$(document).on('show.bs.modal', '.modal', function () {
var zIndex = 1040 + (10 * $('.modal').length);
var model = $(this);
model.css('z-index', zIndex);
model.attr('data-z-index', zIndex);
});
$(document).on('shown.bs.modal', '.modal', function () {
var model = $(this);
var zIndex = model.attr('data-z-index');
model.next('.modal-backdrop.show').css('z-index', zIndex - 1);
});
_x000D_
This is a two-step process:
you need to create a login to SQL Server for that user, based on its Windows account
CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
you need to grant this login permission to access a database:
USE (your database)
CREATE USER (username) FOR LOGIN (your login name)
Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader
database role to read all tables.
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'
You have to have some kind of wrapper around the input to use a before or after pseudo-element. Here's a fiddle that has a before on the wrapper div of an input and then places the before inside the input - or at least it looks like it. Obviously, this is a work around but effective in a pinch and lends itself to being responsive. You can easily make this an after if you need to put some other content.
Working Fiddle
Dollar sign inside an input as a pseudo-element: http://jsfiddle.net/kapunahele/ose4r8uj/1/
The HTML:
<div class="test">
<input type="text"></input>
</div>
The CSS:
input {
margin: 3em;
padding-left: 2em;
padding-top: 1em;
padding-bottom: 1em;
width:20%;
}
.test {
position: relative;
background-color: #dedede;
display: inline;
}
.test:before {
content: '$';
position: absolute;
top: 0;
left: 40px;
z-index: 1;
}
String interning is an optimization technique by the compiler. If you have two identical string literals in one compilation unit then the code generated ensures that there is only one string object created for all the instance of that literal(characters enclosed in double quotes) within the assembly.
I am from C# background, so i can explain by giving a example from that:
object obj = "Int32";
string str1 = "Int32";
string str2 = typeof(int).Name;
output of the following comparisons:
Console.WriteLine(obj == str1); // true
Console.WriteLine(str1 == str2); // true
Console.WriteLine(obj == str2); // false !?
Note1:Objects are compared by reference.
Note2:typeof(int).Name is evaluated by reflection method so it does not gets evaluated at compile time. Here these comparisons are made at compile time.
Analysis of the Results: 1) true because they both contain same literal and so the code generated will have only one object referencing "Int32". See Note 1.
2) true because the content of both the value is checked which is same.
3) FALSE because str2 and obj does not have the same literal. See Note 2.
Any of the following will work:
s = "true"
(s == 'true').real
1
(s == 'false').real
0
(s == 'true').conjugate()
1
(s == '').conjugate()
0
(s == 'true').__int__()
1
(s == 'opal').__int__()
0
def as_int(s):
return (s == 'true').__int__()
>>>> as_int('false')
0
>>>> as_int('true')
1
def quick_sort(l):
if len(l) == 0:
return l
pivot = l[0]
pivots = [x for x in l if x == pivot]
smaller = quick_sort([x for x in l if x < pivot])
larger = quick_sort([x for x in l if x > pivot])
return smaller + pivots + larger
java.util.Scanner; util - package, Scanner - Class
next()
reads the string before the space. it cannot read anything after it gets the first space.nextLine()
reads the whole line. Read until the end of the line or "/n".
Note: Not The Next line(Example)
My mission in life is not merely to survive, but to thrive;
and to do so with some passion, some compassion, some humor.
(Output)
My
My mission in life is not merely to survive, but to thrive;
Tricks:
If you want to read the next line Check Java has
method.
while (scanner.hasNext()) {
scan.next();
}
while (scanner.hasNext()) {
scan.nextLine();
}
Just call it and supply self
class A:
def m(self, x, y):
print(x+y)
class B:
def call_a(self):
A.m(self, 1, 2)
b = B()
b.call_a()
output: 3
You can try the external lib called "sh" (http://amoffat.github.io/sh/).
import sh
print sh.which('ls') # prints '/bin/ls' depending on your setup
print sh.which('xxx') # prints None
If you want to set the precision for all decimals
in EF6 you could replace the default DecimalPropertyConvention
convention used in the DbModelBuilder
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<DecimalPropertyConvention>();
modelBuilder.Conventions.Add(new DecimalPropertyConvention(38, 18));
}
The default DecimalPropertyConvention
in EF6 maps decimal
properties to decimal(18,2)
columns.
If you only want individual properties to have a specified precision then you can set the precision for the entity's property on the DbModelBuilder
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>().Property(e => e.Value).HasPrecision(38, 18);
}
Or, add an EntityTypeConfiguration<>
for the entity which specifies the precision:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new MyEntityConfiguration());
}
internal class MyEntityConfiguration : EntityTypeConfiguration<MyEntity>
{
internal MyEntityConfiguration()
{
this.Property(e => e.Value).HasPrecision(38, 18);
}
}
extension UIImage {
func fixImageOrientation() -> UIImage {
UIGraphicsBeginImageContext(self.size)
self.draw(at: .zero)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage ?? self
}
}
Call it: imageView.image?.fixImageOrientation()
or UIImage(named: "someImage").fixImageOrientation()
Good luck all!
You also can Redirect
within the Route
as follows. This is for handle invalid routes.
<Route path='*' render={() =>
(
<Redirect to="/error"/>
)
}/>
None of those worked for me in Chrome 42...
Instead my directive now uses this link
function (base64
made it work):
link: function(scope, element, attrs) {
var downloadFile = function downloadFile() {
var filename = scope.getFilename();
var link = angular.element('<a/>');
link.attr({
href: 'data:attachment/csv;base64,' + encodeURI($window.btoa(scope.csv)),
target: '_blank',
download: filename
})[0].click();
$timeout(function(){
link.remove();
}, 50);
};
element.bind('click', function(e) {
scope.buildCSV().then(function(csv) {
downloadFile();
});
scope.$apply();
});
}
The solutions proposed by people in this post works or not mainly depending on the Android version of your device. For Example to use the AddAll method you have to put android:minSdkVersion="10" in your android device.
To solve this questions for all devices I have created my on own method in my adapter and use inside the add and remove method inherits from ArrayAdapter that update you data without problems.
My Code: Using my own data class RaceResult, you use your own data model.
ResultGpRowAdapter.java
public class ResultGpRowAdapter extends ArrayAdapter<RaceResult> {
Context context;
int resource;
List<RaceResult> data=null;
public ResultGpRowAdapter(Context context, int resource, List<RaceResult> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.data = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
........
}
//my own method to populate data
public void myAddAll(List<RaceResult> items) {
for (RaceResult item:items){
super.add(item);
}
}
ResultsGp.java
public class ResultsGp extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
...........
...........
ListView list = (ListView)findViewById(R.id.resultsGpList);
ResultGpRowAdapter adapter = new ResultGpRowAdapter(this, R.layout.activity_result_gp_row, new ArrayList<RaceResult>()); //Empty data
list.setAdapter(adapter);
....
....
....
//LOAD a ArrayList<RaceResult> with data
ArrayList<RaceResult> data = new ArrayList<RaceResult>();
data.add(new RaceResult(....));
data.add(new RaceResult(....));
.......
adapter.myAddAll(data); //Your list will be udpdated!!!
Here it is:
[chr(i) for i in xrange(127)]
None of these issues solved this for me. The problem in the end was pretty easy. It looks like its a pretty major Xcode bug which I have logged the problem and fix under Apple bug: 29820370. If you are struggling (as it seems like there are several pages of problems similar to this ) then it would be great if you can raise a bug on bug reporter: https://bugreport.apple.com/ and reference the bug I raised to gain visibility. I want to make Xcode back into the pleasure that it was before - and this is something I am sure Xcode should have fixed itself.
Here is the fix: 1. Open Keychain - go to Apple Worldwide Developer Cert. 2. Double Click on it 3. Change the permission level from "always trust" to use System Defaults 4. Save and close it 5. Restart Xcode, Clean and build your project and it should be gone.
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
if you're trying to use jQuery autocomplete plugin, then I think you don't need to bind to onChange event, it will
You can delete a particular single line with its line number by
sed -i '33d' file
This will delete the line on 33 line number and save the updated file.
from the SimpleDateFormat java doc:
* <td><code>"yyyyy.MMMMM.dd GGG hh:mm aaa"</code>
* <td><code>02001.July.04 AD 12:08 PM</code>
* <td><code>"EEE, d MMM yyyy HH:mm:ss Z"</code>
* <td><code>Wed, 4 Jul 2001 12:08:56 -0700</code>
In iOS10, there's a built in property for this now: timeControlStatus
For example, this function plays or pauses the avPlayer based on it's status and updates the play/pause button appropriately.
@IBAction func btnPlayPauseTap(_ sender: Any) {
if aPlayer.timeControlStatus == .playing {
aPlayer.pause()
btnPlay.setImage(UIImage(named: "control-play"), for: .normal)
} else if aPlayer.timeControlStatus == .paused {
aPlayer.play()
btnPlay.setImage(UIImage(named: "control-pause"), for: .normal)
}
}
As for your second question, to know if the avPlayer reached the end, the easiest thing to do would be to set up a notification.
NotificationCenter.default.addObserver(self, selector: #selector(self.didPlayToEnd), name: .AVPlayerItemDidPlayToEndTime, object: nil)
When it gets to the end, for example, you can have it rewind to the beginning of the video and reset the Pause button to Play.
@objc func didPlayToEnd() {
aPlayer.seek(to: CMTimeMakeWithSeconds(0, 1))
btnPlay.setImage(UIImage(named: "control-play"), for: .normal)
}
These examples are useful if you're creating your own controls, but if you use a AVPlayerViewController, then the controls come built in.
i faced the same problem , the solution worked for me , hope it will work for you too.
<script src="content/js/jquery.min.js"></script>
<script src="content/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
$('.dropdown-toggle').dropdown();
});
</script>
Please include the "jquery.min.js" file before "bootstrap.min.js" file, if you shuffle the order it will not work.
Here is an expanded answer. A DecoratedBox
is what you need to add a border, but I am using a Container
for the convenience of adding margin and padding.
Here is the general setup.
Widget myWidget() {
return Container(
margin: const EdgeInsets.all(30.0),
padding: const EdgeInsets.all(10.0),
decoration: myBoxDecoration(), // <--- BoxDecoration here
child: Text(
"text",
style: TextStyle(fontSize: 30.0),
),
);
}
where the BoxDecoration
is
BoxDecoration myBoxDecoration() {
return BoxDecoration(
border: Border.all(),
);
}
These have a border width of 1
, 3
, and 10
respectively.
BoxDecoration myBoxDecoration() {
return BoxDecoration(
border: Border.all(
width: 1, // <--- border width here
),
);
}
These have a border color of
Colors.red
Colors.blue
Colors.green
Code
BoxDecoration myBoxDecoration() {
return BoxDecoration(
border: Border.all(
color: Colors.red, // <--- border color
width: 5.0,
),
);
}
These have a border side of
Code
BoxDecoration myBoxDecoration() {
return BoxDecoration(
border: Border(
left: BorderSide( // <--- left side
color: Colors.black,
width: 3.0,
),
top: BorderSide( // <--- top side
color: Colors.black,
width: 3.0,
),
),
);
}
These have border radii of 5
, 10
, and 30
respectively.
BoxDecoration myBoxDecoration() {
return BoxDecoration(
border: Border.all(
width: 3.0
),
borderRadius: BorderRadius.all(
Radius.circular(5.0) // <--- border radius here
),
);
}
DecoratedBox
/BoxDecoration
are very flexible. Read Flutter — BoxDecoration Cheat Sheet for many more ideas.
You could just divide your two numbers and multiply by 100. Note that this will throw an error if "whole" is 0, as asking what percentage of 0 a number is does not make sense:
def percentage(part, whole):
return 100 * float(part)/float(whole)
Or with a % at the end:
def percentage(part, whole):
Percentage = 100 * float(part)/float(whole)
return str(Percentage) + “%”
Or if the question you wanted it to answer was "what is 5% of 20", rather than "what percentage is 5 of 20" (a different interpretation of the question inspired by Carl Smith's answer), you would write:
def percentage(percent, whole):
return (percent * whole) / 100.0
I do it like this:
(Shortened the code a bit)
public struct Age
{
public readonly int Years;
public readonly int Months;
public readonly int Days;
}
public Age( int y, int m, int d ) : this()
{
Years = y;
Months = m;
Days = d;
}
public static Age CalculateAge ( DateTime birthDate, DateTime anotherDate )
{
if( startDate.Date > endDate.Date )
{
throw new ArgumentException ("startDate cannot be higher then endDate", "startDate");
}
int years = endDate.Year - startDate.Year;
int months = 0;
int days = 0;
// Check if the last year, was a full year.
if( endDate < startDate.AddYears (years) && years != 0 )
{
years--;
}
// Calculate the number of months.
startDate = startDate.AddYears (years);
if( startDate.Year == endDate.Year )
{
months = endDate.Month - startDate.Month;
}
else
{
months = ( 12 - startDate.Month ) + endDate.Month;
}
// Check if last month was a complete month.
if( endDate < startDate.AddMonths (months) && months != 0 )
{
months--;
}
// Calculate the number of days.
startDate = startDate.AddMonths (months);
days = ( endDate - startDate ).Days;
return new Age (years, months, days);
}
// Implement Equals, GetHashCode, etc... as well
// Overload equality and other operators, etc...
}
I tried everything here (and some otherplaces), and what worked for me (after doing all of these, the registry changes are mandatory I think) was to change the setting for Icon Overlays\Status Cache from Default to Shell, and I also checked "Show overlays and context menu only in explorer". Not sure which of those two did it but it works now.
I see this have been answered. However, I ran into the same issue and fixed it by adding the following to the header of the php script.
header("Pragma: no-cache");
Post/Redirect/Get is a good practice no doubt. But even without that, the above should fix the issue.
You can use the finish
command.
finish
: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated asfin
.
(See 5.2 Continuing and Stepping.)
In Python 3,
urllib2
was replaced by two in-built modules namedurllib.request
andurllib.error
Adapted from source
So replace this:
import urllib2
With this:
import urllib.request as urllib2
Specify all fields but your ID field.
INSERT INTO MyTable (FIELD2, FIELD3, ..., FIELD529, PreviousId)
SELECT FIELD2, NULL, ..., FIELD529, FIELD1
FROM MyTable
WHERE FIELD1 = @Id;
I know that there is already a solution to this question, but I found an alternative to this issue and maybe it could help someone.
I was having trouble with setting the frame of my sub view because certain values were referring to its position within the main view. So if you don't want to update your frame by changing the whole frame via CGRect, you can simply change a value of the frame and then update it.
// keep reference to you frames
var questionView = questionFrame.frame
var answerView = answerFrame.frame
// update the values of the copy
questionView.size.height = CGFloat(screenSize.height * 0.70)
answerView.size.height = CGFloat(screenSize.height * 0.30)
// set the frames to the new frames
questionFrame.frame = questionView
answerFrame.frame = answerView
You cannot prevent the process on the far end of a pipe from exiting, and if it exits before you've finished writing, you will get a SIGPIPE signal. If you SIG_IGN the signal, then your write will return with an error - and you need to note and react to that error. Just catching and ignoring the signal in a handler is not a good idea -- you must note that the pipe is now defunct and modify the program's behaviour so it does not write to the pipe again (because the signal will be generated again, and ignored again, and you'll try again, and the whole process could go on for a long time and waste a lot of CPU power).
This will not expand the last column of the xaml grid to take the remaining space if
AutoGeneratedColumns="True"
.
The parameter tomcat.util.http.parser.HttpParser.requestTargetAllow
is deprecated since Tomcat 8.5: tomcat official doc.
You can use relaxedQueryChars / relaxedPathChars
in the connectors definition to allow these chars: tomcat official doc.
Also running this command in terminal can help find the problem:
gradlew build > log.txt 2>details.txt
then you should go to gradlew file location in read two above log files.
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
If someone is having issues with creating tables by using files dedicated to each model, be aware of running the "create_all" function from a file different from the one where that function is declared. So, if the filesystem is like this:
Root
--app.py <-- file from which app will be run
--models
----user.py <-- file with "User" model
----order.py <-- file with "Order" model
----database.py <-- file with database and "create_all" function declaration
Be careful about calling the "create_all" function from app.py.
This concept is explained better by the answer to this thread posted by @SuperShoot
Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript.
The CSS:
.carousel .item {-webkit-transition: opacity 3s; -moz-transition: opacity 3s; -ms-transition: opacity 3s; -o-transition: opacity 3s; transition: opacity 3s;}
.carousel .active.left {left:0;opacity:0;z-index:2;}
.carousel .next {left:0;opacity:1;z-index:1;}
I noticed however that the transition end event was firing prematurely with the default interval of 5s and a fade transition of 3s. Bumping the carousel interval to 8s provides a nice effect.
Very smooth.
Use TimeSpan.Parse
to convert the string
http://msdn.microsoft.com/en-us/library/system.timespan.parse(v=vs.110).aspx
Use the PHP function serialize()
to convert arrays to strings. These strings can easily be stored in MySQL database. Using unserialize()
they can be converted to arrays again if needed.
Using STS 3.9.1 I got the same problem. However, currently I do not require any new JUnit5 features, so I tried to force using an older version. If using maven, you can add following dependencies to your pom.xml:
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit.vintage.version}</version>
<scope>test</scope>
</dependency>
This did the trick for me (at least as long as I do not need JUnit5 explicitly).
In res/color
place a file "text_selector.xml":
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/blue" android:state_focused="true" />
<item android:color="@color/blue" android:state_selected="true" />
<item android:color="@color/green" />
</selector>
Then in TextView
use it:
<TextView
android:id="@+id/value_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Text"
android:textColor="@color/text_selector"
android:textSize="15sp"
/>
And in code you'll need to set a click listener.
private var isPressed = false
private fun TextView.setListener() {
this.setOnClickListener { v ->
run {
if (isPressed) {
v.isSelected = false
v.clearFocus()
} else {
v.isSelected = true
v.requestFocus()
}
isPressed = !isPressed
}
}
}
override fun onResume() {
super.onResume()
textView.setListener()
}
override fun onPause() {
textView.setOnClickListener(null)
super.onPause()
}
Sorry if there are errors, I changed a code before publishing and didn't check.
The previous answer is correct but in this specific case I would recommend using the System.IO.Path.Combine method.
You can find more details here: http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx
Here is another variation using views:
CREATE VIEW digits AS
SELECT 0 AS digit UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9;
CREATE VIEW numbers AS
SELECT
ones.digit + tens.digit * 10 + hundreds.digit * 100 + thousands.digit * 1000 AS number
FROM
digits as ones,
digits as tens,
digits as hundreds,
digits as thousands;
CREATE VIEW dates AS
SELECT
SUBDATE(CURRENT_DATE(), number) AS date
FROM
numbers;
And then you can simply do (see how elegant it is?):
SELECT
date
FROM
dates
WHERE
date BETWEEN '2010-01-20' AND '2010-01-24'
ORDER BY
date
Update
It is worth noting that you will only be able to generate past dates starting from the current date. If you want to generate any kind of dates range (past, future, and in between), you will have to use this view instead:
CREATE VIEW dates AS
SELECT
SUBDATE(CURRENT_DATE(), number) AS date
FROM
numbers
UNION ALL
SELECT
ADDDATE(CURRENT_DATE(), number + 1) AS date
FROM
numbers;
Using array formula.
=SUM(COUNT(IF(D1:D5="Yes",COUNT(D1:D5),"")),COUNT(IF(D1:D5="No",COUNT(D1:D5),"")),COUNT(IF(D1:D5="Agree",COUNT(D1:D5),"")))
PRESS = CTRL + SHIFT + ENTER.
For Debian/Ubuntu:
sudo apt-get install php7.0-mbstring
just serialize the form data and get your problem solved.
data: $('#form_id').serialize(),
During these peak CPU times, what is the user load like? You say this is a web based application, so the culprits that come to mind is memory utilization issues. If you store a lot of stuff in the session, for instance, and the session count gets high enough, the app server will start thrashing about. This is also a case where the GC might make matters worse depending on the scheme you are using. More information about the app and the server configuration would be helpful in pointing towards more debugging ideas.
These two approaches produce identical dictionaries, except, as you've noted, where the lexical rules of Python interfere.
Dictionary literals are a little more obviously dictionaries, and you can create any kind of key, but you need to quote the key names. On the other hand, you can use variables for keys if you need to for some reason:
a = "hello"
d = {
a: 'hi'
}
The dict()
constructor gives you more flexibility because of the variety of forms of input it takes. For example, you can provide it with an iterator of pairs, and it will treat them as key/value pairs.
I have no idea why PyCharm would offer to convert one form to the other.
This article on MSDN references a number of type aliases (available on Windows) that are a bit more explicit with respect to their width:
http://msdn.microsoft.com/en-us/library/aa505945.aspx
For instance, although you can use ULONGLONG to reference a 64-bit unsigned integral value, you can also use UINT64. (The same goes for ULONG and UINT32.) Perhaps these will be a bit clearer?
There's more then one way to do this with DateTime which was introduced in PHP 5.2. Unlike using strtotime()
this will account for daylight savings time and leap year.
$datetime = new DateTime('2013-01-29');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');
// Available in PHP 5.3
$datetime = new DateTime('2013-01-29');
$datetime->add(new DateInterval('P1D'));
echo $datetime->format('Y-m-d H:i:s');
// Available in PHP 5.4
echo (new DateTime('2013-01-29'))->add(new DateInterval('P1D'))->format('Y-m-d H:i:s');
// Available in PHP 5.5
$start = new DateTimeImmutable('2013-01-29');
$datetime = $start->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');
Your keys may already be in PEM format, but just named with .crt or .key.
If the file's content begins with -----BEGIN
and you can read it in a text editor:
The file uses base64, which is readable in ASCII, not binary format. The certificate is already in PEM format. Just change the extension to .pem.
If the file is in binary:
For the server.crt, you would use
openssl x509 -inform DER -outform PEM -in server.crt -out server.crt.pem
For server.key, use openssl rsa
in place of openssl x509
.
The server.key is likely your private key, and the .crt file is the returned, signed, x509 certificate.
If this is for a Web server and you cannot specify loading a separate private and public key:
You may need to concatenate the two files. For this use:
cat server.crt server.key > server.includesprivatekey.pem
I would recommend naming files with "includesprivatekey" to help you manage the permissions you keep with this file.
Unique is a keyword used in the Create Table() directive to denote that a field will contain unique data, usually used for natural keys, foreign keys etc.
For example:
Create Table Employee(
Emp_PKey Int Identity(1, 1) Constraint PK_Employee_Emp_PKey Primary Key,
Emp_SSN Numeric Not Null Unique,
Emp_FName varchar(16),
Emp_LName varchar(16)
)
i.e. Someone's Social Security Number would likely be a unique field in your table, but not necessarily the primary key.
Distinct is used in the Select statement to notify the query that you only want the unique items returned when a field holds data that may not be unique.
Select Distinct Emp_LName
From Employee
You may have many employees with the same last name, but you only want each different last name.
Obviously if the field you are querying holds unique data, then the Distinct keyword becomes superfluous.
I hope this will help you!!
form.blade.php
@php
$name = $user->name ?? null;
$email = $user->email ?? null;
$info = $user->info ?? null;
$role = $user->role ?? null;
@endphp
<div class="form-group">
{!! Form::label('name', 'Name') !!}
{!! Form::text('name', $name, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('email', 'Email') !!}
{!! Form::email('email', $email, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('role', 'Função') !!}
{!! Form::text('role', $role, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('info', 'Informações') !!}
{!! Form::textarea('info', $info, ['class' => 'form-control']) !!}
</div>
<a class="btn btn-danger float-right" href="{{ route('users.index') }}">CANCELAR</a>
create.blade.php
@extends('layouts.app')
@section('title', 'Criar usuário')
@section('content')
{!! Form::open(['action' => 'UsersController@store', 'method' => 'POST']) !!}
@include('users.form')
<div class="form-group">
{!! Form::label('password', 'Senha') !!}
{!! Form::password('password', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('password', 'Confirmação de senha') !!}
{!! Form::password('password_confirmation', ['class' => 'form-control']) !!}
</div>
{!! Form::submit('ADICIONAR', array('class' => 'btn btn-primary')) !!}
{!! Form::close() !!}
@endsection
edit.blade.php
@extends('layouts.app')
@section('title', 'Editar usuário')
@section('content')
{!! Form::model($user, ['route' => ['users.update', $user->id], 'method' => 'PUT']) !!}
@include('users.form', compact('user'))
{!! Form::submit('EDITAR', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
<a href="{{route('users.editPassword', $user->id)}}">Editar senha</a>
@endsection
UsersController.php
use App\User;
Class UsersController extends Controller {
#...
public function create()
{
return view('users.create';
}
public function edit($id)
{
$user = User::findOrFail($id);
return view('users.edit', compact('user');
}
}
Just put the two files in the same directory. Here's an example:
Person.java
public class Person {
public String name;
public Person(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
Student.java
public class Student extends Person {
public String somethingnew;
public Student(String name) {
super(name);
somethingnew = "surprise!";
}
public String toString() {
return super.toString() + "\t" + somethingnew;
}
public static void main(String[] args) {
Person you = new Person("foo");
Student me = new Student("boo");
System.out.println("Your name is " + you);
System.out.println("My name is " + me);
}
}
Running Student (since it has the main function) yields us the desired outcome:
Your name is foo
My name is boo surprise!
Use:
+ scale_y_continuous(labels = scales::percent)
Or, to specify formatting parameters for the percent:
+ scale_y_continuous(labels = scales::percent_format(accuracy = 1))
(the command labels = percent
is obsolete since version 2.2.1 of ggplot2)
Okay, little late to the game, but none of these solutions quite did what I was trying to do. These solutions have a couple problems
I wanted a ListView with the grouping headers, and each ListViewItem should just be 'informational' without selection or hover over, but the ListViewItem has a button in it that I want to be click-able and have hover-over.
So, really what I want is the ListViewItem to not be a ListViewItem at all, So, I over rode the ListViewItem's ControlTemplate and just made it a simple ContentControl.
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<ContentControl Content="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
Try:
function initSlider(){
$('.references').slick({
dots: false,
infinite: true,
speed: 300,
slidesToShow: 1,
autoplay: true,
prevArrow: '<div class="slick-prev"><i class="fa fa-chevron-left"></i></div>',
nextArrow: '<div class="slick-next"><i class="fa fa-chevron-right"></i></div>'
});
}
$(document).on('ready', function () {
initSlider();
});
Also just to be sure, make sure that you include the JS file for the slider after you include jQuery and before you include the code above to initialise.
You can also mix raw SQL with ActiveRecord conditions, for example if you want to call a function in a condition:
my_instances = MyModel.where.not(attribute_a: nil) \
.where('crc32(attribute_b) = ?', slot) \
.select(:id)
Use PHP's $_POST
or $_GET
superglobals to retrieve the value of the input tag via the name of the HTML tag.
For Example, change the method in your form and then echo out the value by the name of the input:
Using $_GET
method:
<form name="form" action="" method="get">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_GET['subject']; ?>
Using $_POST
method:
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_POST['subject']; ?>
Use transparent borders if possible.
https://jsfiddle.net/74q3na62/
HTML
<div class="table">
<div class="row">
<div class="cell">Cell 1</div>
<div class="cell">Cell 2</div>
<div class="cell">Cell 3</div>
</div>
</div>
CSS
.table {
display: table;
border: 1px solid black;
}
.row { display:table-row; }
.cell {
display: table-cell;
background-clip: padding-box;
background-color: gold;
border-right: 10px solid transparent;
}
.cell:last-child {
border-right: 0 none;
}
You could use the border-spacing
property, as the accepted answer suggests, but this not only generates space between the table cells but also between the table cells and the table container. This may be unwanted.
If you don't need visible borders on your table cells you should therefore use transparent
borders to generate cell margins. Transparent borders require setting background-clip: padding-box;
because otherwise the background color of the table cells is displayed on the border.
Transparent borders and background-clip are supported in IE9 upwards (and all other modern browsers). If you need IE8 compatibility or don't need actual transparent space you can simply set a white border color and leave the background-clip
out.
Android studio 4.0.1 Kotlin 1.3.72
Android Navigation architecture component.
The following code works for me:
findNavController().popBackStack()
I was getting this error when I was updating the dictionary with the wrong syntax:
Try with these:
lineItem.values.update({attribute,value})
instead of
lineItem.values.update({attribute:value})
This gives capital Letters to all major words
library(lettercase)
xString = str_title_case(xString)
This is shorter and works
<connectionStrings>
<add name="DBConnection"
connectionString="data source=SERVER\INSTANCE;
Initial Catalog=MyDB;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Persist Security Info not needed
There is none. Alas, you have to type out the full type name.
Edit: 7 years after being posted, type inference for local variables (with var
) was added in Java 10.
Edit: 6 years after being posted, to collect some of the comments from below:
The reason C# has the var
keyword is because it's possible to have Types that have no name in .NET. Eg:
var myData = new { a = 1, b = "2" };
In this case, it would be impossible to give a proper type to myData
. 6 years ago, this was impossible in Java (all Types had names, even if they were extremely verbose and unweildy). I do not know if this has changed in the mean time.
var
is not the same as dynamic
. var
iables are still 100% statically typed. This will not compile:
var myString = "foo";
myString = 3;
var
is also useful when the type is obvious from context. For example:
var currentUser = User.GetCurrent();
I can say that in any code that I am responsible for, currentUser
has a User
or derived class in it. Obviously, if your implementation of User.GetCurrent
return an int, then maybe this is a detriment to you.
This has nothing to do with var
, but if you have weird inheritance hierarchies where you shadow methods with other methods (eg new public void DoAThing()
), don't forget that non-virtual methods are affected by the Type they are cast as.
I can't imagine a real world scenario where this is indicative of good design, but this may not work as you expect:
class Foo {
public void Non() {}
public virtual void Virt() {}
}
class Bar : Foo {
public new void Non() {}
public override void Virt() {}
}
class Baz {
public static Foo GetFoo() {
return new Bar();
}
}
var foo = Baz.GetFoo();
foo.Non(); // <- Foo.Non, not Bar.Non
foo.Virt(); // <- Bar.Virt
var bar = (Bar)foo;
bar.Non(); // <- Bar.Non, not Foo.Non
bar.Virt(); // <- Still Bar.Virt
As indicated, virtual methods are not affected by this.
No, there is no non-clumsy way to initialize a var
without an actual variable.
var foo1 = "bar"; //good
var foo2; //bad, what type?
var foo3 = null; //bad, null doesn't have a type
var foo4 = default(var); //what?
var foo5 = (object)null; //legal, but go home, you're drunk
In this case, just do it the old fashioned way:
object foo6;
This does the same, enhanced with CONTAINS:
Function SingleCellExtract(LookupValue As String, LookupRange As Range, ColumnNumber As Integer, Char As String)
Dim I As Long
Dim xRet As String
For I = 1 To LookupRange.Columns(1).Cells.Count
If InStr(1, LookupRange.Cells(I, 1), LookupValue) > 0 Then
If xRet = "" Then
xRet = LookupRange.Cells(I, ColumnNumber) & Char
Else
xRet = xRet & "" & LookupRange.Cells(I, ColumnNumber) & Char
End If
End If
Next
SingleCellExtract = Left(xRet, Len(xRet) - 1)
End Function
Another way
@Html.TextAreaFor(model => model.Comments[0].Comment)
And in your css do this
textarea
{
font-family: inherit;
width: 650px;
height: 65px;
}
That DataType dealie allows carriage returns in the data, not everybody likes those.
That entity is converted to the char it represents when the browser renders the page. JS (jQuery) reads the rendered page, thus it will not encounter such a text sequence. The only way it could encounter such a thing is if you're double encoding entities.
To run Mocha with
mocha
command from your terminal you need to install mocha globally onthis
machine:
npm install --global mocha
Then cd
to your projectFolder/test and run mocha yourTestFileName.js
If you want to make
mocha
available inside yourpackage.json
as a development dependency:
npm install --save-dev mocha
Then add mocha
to your scripts inside package.json
.
"scripts": {
"test": "mocha"
},
Then run npm test
inside your terminal.
You can access 1 line at a time by for loop
#!/bin/bash -eu
#This script prints contents of /etc/passwd line by line
FILENAME='/etc/passwd'
I=0
for LN in $(cat $FILENAME)
do
echo "Line number $((I++)) --> $LN"
done
Copy the entire content to File (say line.sh ) ; Execute
chmod +x line.sh
./line.sh
I am using: Apache Commons Lang: StringUtils.ordinalIndexOf()
StringUtils.ordinalIndexOf("Java Language", "a", 2)
I think may be you should try to convert the data to json format. It can be done by using gson lib. Try something like below.
I don't know it is a best solutions or not but you could do it this way.It worked for me
example : `
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response info(@HeaderParam("Accept") String accept) {
Info information = new Info();
information.setInfo("Calc Application Info");
System.out.println(accept);
if (!accept.equals(MediaType.APPLICATION_JSON)) {
return Response.status(Status.ACCEPTED).entity(information).build();
} else {
Gson jsonConverter = new GsonBuilder().create();
return Response.status(Status.ACCEPTED).entity(jsonConverter.toJson(information)).build();
}
}
Thread
is a lower-level concept: if you're directly starting a thread, you know it will be a separate thread, rather than executing on the thread pool etc.
Task
is more than just an abstraction of "where to run some code" though - it's really just "the promise of a result in the future". So as some different examples:
Task.Delay
doesn't need any actual CPU time; it's just like setting a timer to go off in the futureWebClient.DownloadStringTaskAsync
won't take much CPU time locally; it's representing a result which is likely to spend most of its time in network latency or remote work (at the web server)Task.Run()
really is saying "I want you to execute this code separately"; the exact thread on which that code executes depends on a number of factors.Note that the Task<T>
abstraction is pivotal to the async support in C# 5.
In general, I'd recommend that you use the higher level abstraction wherever you can: in modern C# code you should rarely need to explicitly start your own thread.
Well you certainly can use a List<List<string>>
where you'd then write:
List<string> track = new List<string>();
track.Add("2349");
track.Add("The Prime Time of Your Life");
// etc
matrix.Add(track);
But why would you do that instead of building your own class to represent a track, with Track ID, Name, Artist, Album, Play Count and Skip Count properties? Then just have a List<Track>
.
There is a helper library for this.
Swift 5
pod 'DeviceKit', '~> 2.0'
Swift 4.0 - Swift 4.2
pod 'DeviceKit', '~> 1.3'
if you just want to determine the model and make something accordingly.
You can use like that :
let isIphoneX = Device().isOneOf([.iPhoneX, .simulator(.iPhoneX)])
In a function :
func isItIPhoneX() -> Bool {
let device = Device()
let check = device.isOneOf([.iPhoneX, .iPhoneXr , .iPhoneXs , .iPhoneXsMax ,
.simulator(.iPhoneX), .simulator(.iPhoneXr) , .simulator(.iPhoneXs) , .simulator(.iPhoneXsMax) ])
return check
}
Create a file named "overrideBashCdForWindowsPaths" in your HOME folder. Paste the following lines into that file and save it:
#!/bin/bash
function cd() {
CD_PATH="$(history | tail -1 | sed -e "s,.*${FUNCNAME[0]}\s*,,g")"
if [ -z "${CD_PATH}" -o "${CD_PATH}" = "~" ]; then
CD_PATH="${HOME}"
fi
builtin cd "$(cygpath "$CD_PATH")"
}
Next, type the following command in a terminal, while you are in your HOME folder:
echo ". overrideBashCdForWindowsPaths" >> .bashrc
Close your terminal and open a new one. You can now easily change into that Windows folder by simply typing
cd C:\Python31\sip
The script reads the last command, extracts the path and passes it to Cygwin's path-conversion tool. By naming the function "cd" we sort of 'override' Bash's builtin "cd" and delegate the actual call to it in the very last line.
Change your markup slightly:
$(function() {_x000D_
enable_cb();_x000D_
$("#group1").click(enable_cb);_x000D_
});_x000D_
_x000D_
function enable_cb() {_x000D_
if (this.checked) {_x000D_
$("input.group1").removeAttr("disabled");_x000D_
} else {_x000D_
$("input.group1").attr("disabled", true);_x000D_
}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form name="frmChkForm" id="frmChkForm">_x000D_
<input type="checkbox" name="chkcc9" id="group1">Check Me <br>_x000D_
<input type="checkbox" name="chk9[120]" class="group1"><br>_x000D_
<input type="checkbox" name="chk9[140]" class="group1"><br>_x000D_
<input type="checkbox" name="chk9[150]" class="group1"><br>_x000D_
</form>
_x000D_
You can do this using attribute selectors without introducing the ID and classes but it's slower and (imho) harder to read.
I have solution without adapter. Transient map converted to xml-elements and vise versa:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "SchemaBasedProperties")
public class SchemaBasedProperties
{
@XmlTransient
Map<String, Map<String, String>> properties;
@XmlAnyElement(lax = true)
List<Object> xmlmap;
public Map<String, Map<String, String>> getProperties()
{
if (properties == null)
properties = new LinkedHashMap<String, Map<String, String>>(); // I want same order
return properties;
}
boolean beforeMarshal(Marshaller m)
{
try
{
if (properties != null && !properties.isEmpty())
{
if (xmlmap == null)
xmlmap = new ArrayList<Object>();
else
xmlmap.clear();
javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
org.w3c.dom.Document doc = db.newDocument();
org.w3c.dom.Element element;
Map<String, String> attrs;
for (Map.Entry<String, Map<String, String>> it: properties.entrySet())
{
element = doc.createElement(it.getKey());
attrs = it.getValue();
if (attrs != null)
for (Map.Entry<String, String> at: attrs.entrySet())
element.setAttribute(at.getKey(), at.getValue());
xmlmap.add(element);
}
}
else
xmlmap = null;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
void afterUnmarshal(Unmarshaller u, Object p)
{
org.w3c.dom.Node node;
org.w3c.dom.NamedNodeMap nodeMap;
String name;
Map<String, String> attrs;
getProperties().clear();
if (xmlmap != null)
for (Object xmlNode: xmlmap)
if (xmlNode instanceof org.w3c.dom.Node)
{
node = (org.w3c.dom.Node) xmlNode;
nodeMap = node.getAttributes();
name = node.getLocalName();
attrs = new HashMap<String, String>();
for (int i = 0, l = nodeMap.getLength(); i < l; i++)
{
node = nodeMap.item(i);
attrs.put(node.getNodeName(), node.getNodeValue());
}
getProperties().put(name, attrs);
}
xmlmap = null;
}
public static void main(String[] args)
throws Exception
{
SchemaBasedProperties props = new SchemaBasedProperties();
Map<String, String> attrs;
attrs = new HashMap<String, String>();
attrs.put("ResId", "A_LABEL");
props.getProperties().put("LABEL", attrs);
attrs = new HashMap<String, String>();
attrs.put("ResId", "A_TOOLTIP");
props.getProperties().put("TOOLTIP", attrs);
attrs = new HashMap<String, String>();
attrs.put("Value", "hide");
props.getProperties().put("DISPLAYHINT", attrs);
javax.xml.bind.JAXBContext jc = javax.xml.bind.JAXBContext.newInstance(SchemaBasedProperties.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(props, new java.io.File("test.xml"));
Unmarshaller unmarshaller = jc.createUnmarshaller();
props = (SchemaBasedProperties) unmarshaller.unmarshal(new java.io.File("test.xml"));
System.out.println(props.getProperties());
}
}
My output as espected:
<SchemaBasedProperties>
<LABEL ResId="A_LABEL"/>
<TOOLTIP ResId="A_TOOLTIP"/>
<DISPLAYHINT Value="hide"/>
</SchemaBasedProperties>
{LABEL={ResId=A_LABEL}, TOOLTIP={ResId=A_TOOLTIP}, DISPLAYHINT={Value=hide}}
You can use element name/value pair. I need attributes... Have fun!
There's also the json_spec gem, which is worth a look
your markup was a bit messed up. Here's the styles you need and proper html
CSS:
.navbar-brand,
.navbar-nav li a {
line-height: 150px;
height: 150px;
padding-top: 0;
}
HTML:
<nav class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><img src="img/logo.png" /></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="">Portfolio</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Contact</a></li>
</ul>
</div>
</nav>
Or check out the fiddle at: http://jsfiddle.net/TP5V8/1/
The best approach if you want to ALWAYS show two decimal places (even if your number only has one decimal place) is to use
yournumber.ToString("0.00");
The ==
operator checks to see if the two strings are exactly the same object.
The .equals()
method will check if the two strings have the same value.
You can use these methods to get an empty guid. The result will be a guid with all it's digits being 0's - "00000000-0000-0000-0000-000000000000
".
new Guid()
default(Guid)
Guid.Empty
Why does it work in Chrome and not Firefox?
The W3 spec for CORS preflight requests clearly states that user credentials should be excluded. There is a bug in Chrome and WebKit where OPTIONS
requests returning a status of 401 still send the subsequent request.
Firefox has a related bug filed that ends with a link to the W3 public webapps mailing list asking for the CORS spec to be changed to allow authentication headers to be sent on the OPTIONS
request at the benefit of IIS users. Basically, they are waiting for those servers to be obsoleted.
How can I get the OPTIONS
request to send and respond consistently?
Simply have the server (API in this example) respond to OPTIONS
requests without requiring authentication.
Kinvey did a good job expanding on this while also linking to an issue of the Twitter API outlining the catch-22 problem of this exact scenario interestingly a couple weeks before any of the browser issues were filed.
First you need to know the exact name of the INDEX (Unique key in this case) to delete or update it.
INDEX names are usually same as column names. In case of more than one INDEX applied on a column, MySQL automatically suffixes numbering to the column names to create unique INDEX names.
For example if 2 indexes are applied on a column named customer_id
customer_id
itself.customer_id_2
and so on.SHOW INDEX FROM <table_name>
as suggested by @Amr
ALTER TABLE <table_name> DROP INDEX <index_name>;
Like ctrlplusb said, I recommend you to use the package dotenv
, but another way to do this is creating a js file and requiring it on the first line of your app server.
env.js:
process.env.VAR1="Some value"
process.env.VAR2="Another Value"
app.js:
require('env')
console.log(process.env.VAR1) // Some value
I think your problem lies because of the profile that you were using xCode4.6 and now you are using xCode5.
You need to refresh certificates/provisioning profiles via XCode > Preferences > Accounts
XCode > Preferences > Accounts > Click on your DEV ACCOUNT > View Details button (bottom right) > Signing Iden/PPs screen appears > hit Refresh.
Then choose again from build settings the correct profile and clean and build your project.
Hope this helps you.
This language feature is convenient in this situation.
public String getName() {
return (String) memberHashMap.get("Name");
}
If memberHashMap.get("Name") returns null, you'd still want the method above to return null without throwing an exception. No matter what the class is, null is null.