To add to the answer.
declare
v_result clob;
begin
---- some operation on v_result
dbms_lob.substr( v_result, 4000 ,length(v_result) - 3999 );
end;
/
In dbms_lob.substr
first parameter
is clob
which you want to extract .
Second parameter
is how much length of clob you want to extract.
Third parameter
is from which word you want to extract .
In above example i know my clob size is more than 50000 , so i want last 4000 character .
You can use array_slice as:
$sliced_array = array_slice($array,0,$N);
I think I just found a way to read MAC addresses without LOCATION permission: Run ip link
and parse its output. (you could probably do the similar by looking at this binary's source code)
You can use the asList
method with varargs to do this in one line:
java.util.Arrays.asList('+', '-', '*', '^');
If the list does not need to be modified further then this would already be enough. Otherwise you can pass it to the ArrayList constructor to create a mutable list:
new ArrayList(Arrays.asList('+', '-', '*', '^'));
You'll want to do get a Calendar instance and get it's day of month
Calendar cal = Calendar.getInstance();
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
String dayOfMonthStr = String.valueOf(dayOfMonth);
You can also get DAY_OF_WEEK, DAY_OF_YEAR, DAY_OF_WEEK_IN_MONTH, etc.
Simply using re.sub
might also work instead of str.maketrans
. And this would also work in python 2.x
>>> print(re.sub(r'(\-|\]|\^|\$|\*|\.|\\)',lambda m:{'-':'\-',']':'\]','\\':'\\\\','^':'\^','$':'\$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\\w\$arr=1
In gcc, this isn't supported. In fact, this isn't supported in any existing compiler/linker i'm aware of.
if Your Android Studio Version Greater than 3.0
Looks like we can not directly use the apk after running on the device from the build -->output->apk folder.
After upgrading to android studio 3.0 you need to go to Build -> Build Apk(s) then copy the apk from build -> output -> apk -> debug
You can use a struct to read write into a file. You do not need to cast it as a `char*. Struct size will also be preserved. (This point is not closest to the topic but guess it: behaving on hard memory is often similar to RAM one.)
To move (to & from) a single string field you must use strncpy
and a transient string buffer '\0'
terminating.
Somewhere you must remember the length of the record string field.
To move other fields you can use the dot notation, ex.:
NodeB->one=intvar;
floatvar2=(NodeA->insidebisnode_subvar).myfl;
struct mynode {
int one;
int two;
char txt3[3];
struct{char txt2[6];}txt2fi;
struct insidenode{
char txt[8];
long int myl;
void * mypointer;
size_t myst;
long long myll;
} insidenode_subvar;
struct insidebisnode{
float myfl;
} insidebisnode_subvar;
} mynode_subvar;
typedef struct mynode* Node;
...(main)
Node NodeA=malloc...
Node NodeB=malloc...
You can embed each string into a structs that fit it,
to evade point-2 and behave like Cobol:
NodeB->txt2fi=NodeA->txt2fi
...but you will still need of a transient string
plus one strncpy
as mentioned at point-2 for scanf
, printf
otherwise an operator longer input (shorter),
would have not be truncated (by spaces padded).
(NodeB->insidenode_subvar).mypointer=(NodeA->insidenode_subvar).mypointer
will create a pointer alias.NodeB.txt3=NodeA.txt3
causes the compiler to reject:
error: incompatible types when assigning to type ‘char[3]’ from type ‘char *’
point-4 works only because NodeB->txt2fi
& NodeA->txt2fi
belong to the same typedef
!!
A correct and simple answer to this topic I found at In C, why can't I assign a string to a char array after it's declared? "Arrays (also of chars) are second-class citizens in C"!!!
Use strtotime()
on your first date then date('Y-m-d')
to convert it back:
$time = strtotime('10/16/2003');
$newformat = date('Y-m-d',$time);
echo $newformat;
// 2003-10-16
Make note that there is a difference between using forward slash /
and hyphen -
in the strtotime()
function. To quote from php.net:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
Like the answer as SET don't have duplicate value and List can. Of course, order is another one thing to different them apart.
To create a label for text:
JLabel label1 = new JLabel("Test");
To change the text in the label:
label1.setText("Label Text");
And finally to clear the label:
label1.setText("");
And all you have to do is place the label in your layout, or whatever layout system you are using, and then just add it to the JFrame...
Need To Two Or More Parameters Passing Throw view To Controller Use This Syntax... Try.. It.
var id=0,Num=254;var str='Sample';
var Url = '@Url.Action("ViewNameAtController", "Controller", new RouteValueDictionary(new { id= "id", Num= "Num", Str= "str" }))'.replace("id", encodeURIComponent(id));
Url = Url.replace("Num", encodeURIComponent(Num));
Url = Url.replace("Str", encodeURIComponent(str));
Url = Url.replace(/&/g, "&");
window.location.href = Url;
In my case I was doing show / hide elements of a form according to whether an input element was empty or not, so that when hiding the elements the element following the hidden ones was repositioned occupying its space it was necessary to do a float: left of the element of such an element. Even using a plugin as dependsOn it was necessary to use float.
import java.awt.MouseInfo;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class MyClass {
public static void main(String[] args) throws InterruptedException{
while(true){
//Thread.sleep(100);
System.out.println("(" + MouseInfo.getPointerInfo().getLocation().x +
", " +
MouseInfo.getPointerInfo().getLocation().y + ")");
}
}
}
I found this note in the end of the lt() docs:
Additional Notes:
Because :lt() is a jQuery extension and not part of the CSS specification, queries using :lt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(0, index) instead.
So use $("selector").slice(from, to)
for better performances.
The only thing that worked for me is:
sudo install_name_tool -change libmysqlclient.18.dylib \
/usr/local/mysql-5.6.23-osx10.8-x86_64/lib/libmysqlclient.18.dylib \
/Library/Ruby/Gems/2.0.0/gems/mysql2-0.4.3/lib/mysql2/mysql2.bundle
Replace the paths of mysql and gems to fit your system.
We do not need any import to do this. This also works much faster
def is_valid_ip(str_ip_addr):
"""
:return: returns true if IP is valid, else returns False
"""
ip_blocks = str(str_ip_addr).split(".")
if len(ip_blocks) == 4:
for block in ip_blocks:
# Check if number is digit, if not checked before calling this function
if not block.isdigit():
return False
tmp = int(block)
if 0 > tmp > 255:
return False
return True
return False
I just had this issue and solved it by editing mail.php under config folder. Usually when using shared hosting, they hosting company allows you to create an email such as
. So go to email settings under you shared hosting cpanel and add new email. Take that email and password and set it in the
mail.php.
It should work!
I want to say this goes against the "conventional wisdom", but I generally prefer to use size. The reason for this is precisely the reason that many people say not to: the width of the field will vary from browser to browser, depending on font size. Specifically, it will always be large enough to display the specified number of characters, regardless of browser settings.
For example, if I have a date field, I typically want the field wide enough to display either 8 or 10 characters (two digit month and day and either two or four digit year, with separators). Setting the size attribute essentially guarantees me that the entire date will be visible, with minimal wasted space. Similarly for most numbers - I know the range of values expected, so I'll set the size attribute to the proper number of digits, plus decimal point if applicable.
As far as I can tell, no CSS attribute does this. Setting a width in em, for example, is based off the height, not the width, and thus is not very precise if you want to display a known number of characters.
Of course, this logic doesn't always apply - a name entry field, for example, could contain any number of characters. In those cases I'll fall back to CSS width properties, typically in px. However, I would say the majority of fields I make have some sort of known content, and by specifying the size attribute I can make sure that most of the content, in most cases, is displayed without clipping.
To count the number of lines matched the pattern:
grep -n "Pattern" in_file.ext | wc -l
To extract matched pattern
sed -n '/pattern/p' file.est
To display line numbers on which pattern was matched
grep -n "pattern" file.ext | cut -f1 -d:
Short answer for the code in question is:
UPDATE `table` SET test=number
Here table
is the table name and it's surrounded by grave accent (aka back-ticks `) as this is MySQL convention to escape keywords (and TABLE
is a keyword in that case).
BEWARE, that this is pretty dangerous query which will wipe everything in column test
in every row of your table replacing it by the number
(regardless of it's value)
It is more common to use WHERE
clause to limit your query to only specific set of rows:
UPDATE `products` SET `in_stock` = true WHERE `supplier_id` = 10
In order to run ssh-add
on Windows one could install git using choco install git
. The ssh-add
command is recognized once C:\Program Files\Git\usr\bin
has been added as a PATH variable and the command prompt has been restarted:
C:\Users\user\Desktop\repository>ssh-add .ssh/id_rsa
Enter passphrase for .ssh/id_rsa:
Identity added: .ssh/id_rsa (.ssh/id_rsa)
C:\Users\user\Desktop\repository>
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.Number = 12;
MyDynamic.MyMethod = new Func<int>(() =>
{
return 55;
});
Console.WriteLine(MyDynamic.MyMethod());
Read more about ExpandoObject class and for more samples: Represents an object whose members can be dynamically added and removed at run time.
100% alphanumeric RegEx (it contains only alphanumeric, not even integers & characters, only alphanumeric)
For example:
special char (not allowed)
123 (not allowed)
asdf (not allowed)
1235asdf (allowed)
String name="^[^<a-zA-Z>]\\d*[a-zA-Z][a-zA-Z\\d]*$";
If your goal is to simply display some static files you can use the Connect package. I have had some success (I'm still pretty new to NodeJS myself), using it and the twitter bootstrap API in combination.
at the command line
:\> cd <path you wish your server to reside>
:\> npm install connect
Then in a file (I named) Server.js
var connect = require('connect'),
http = require('http');
connect()
.use(connect.static('<pathyouwishtoserve>'))
.use(connect.directory('<pathyouwishtoserve>'))
.listen(8080);
Finally
:\>node Server.js
Caveats:
If you don't want to display the directory contents, exclude the .use(connect.directory line.
So I created a folder called "server" placed index.html in the folder and the bootstrap API in the same folder. Then when you access the computers IP:8080 it's automagically going to use the index.html file.
If you want to use port 80 (so just going to http://, and you don't have to type in :8080 or some other port). you'll need to start node with sudo, I'm not sure of the security implications but if you're just using it for an internal network, I don't personally think it's a big deal. Exposing to the outside world is another story.
I haven't had to do the following on my latest versions of things, so try it out like above first, if it doesn't work (and you read the errors complaining it can't find nodejs), go ahead and possibly try the below.
Additionally when running in ubuntu I ran into a problem using nodejs as the name (with NPM), if you're having this problem, I recommend using an alias or something to "rename" nodejs to node.
Commands I used (for better or worse):
Create a new file called node
:\>gedit /usr/local/bin/node
#!/bin/bash
exec /nodejs "$@"
sudo chmod -x /usr/local/bin/node
That ought to make
node Server.js
work just fine
On macOS Sierra you need to run:
sudo chown -R $(whoami):staff /usr/local
If you use this, check man sudo
too:
#!/bin/bash
sudo echo "Hi, I'm root"
sudo -u nobody echo "I'm nobody"
sudo -u 1000 touch /test_user
Google's Guava library also has a copy method:
public static void copy(File from, File to) throws IOException
Warning: If to
represents an existing file, that file
will be overwritten with the contents of from
. If to
and
from
refer to the same file, the contents of that file
will be deleted.
Parameters:from
- the source fileto
- the destination file
Throws:
IOException
- if an I/O error occurs
IllegalArgumentException
- if from.equals(to)
I changed 3 things and then it works:
From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.
The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.
If this issue is causing serious problems, here are a few things I would suggest:
Revert back to JDK 1.7.0_25 until a fix is added to the JDK.
Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.
Try the JDK early releases as they come out. One of them might fix your problem.
Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.
in this way it can be checked whether such a key is available
if (Session.Dictionary.ContainsKey("Sessionkey")) --> return Bool
The accepted answer shows the correct way to setState but it does not lead to a well functioning select box.
import React, { useState } from "react";
import ReactDOM from "react-dom";
const initialValue = { id: 0,value: " --- Select a State ---" };
const options = [
{ id: 1, value: "Alabama" },
{ id: 2, value: "Georgia" },
{ id: 3, value: "Tennessee" }
];
const StateSelector = () => {
const [ selected, setSelected ] = useState(initialValue);
return (
<div>
<label>Select a State:</label>
<select value={selected}>
{selected === initialValue &&
<option disabled value={initialValue}>{initialValue.value}</option>}
{options.map((localState, index) => (
<option key={localState.id} value={localState}>
{localState.value}
</option>
))}
</select>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);
Yes, people use these terms interchangeably with regard to MySQL. Though oftentimes you will hear people inappropriately refer to the entire database server as the database.
Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1')
change day/month position.
That particular package does not include assemblies for dotnet core, at least not at present. You may be able to build it for core yourself with a few tweaks to the project file, but I can't say for sure without diving into the source myself.
Well, this question appears on top of search results, so I believe we need code example here. Here's the Python code:
import cv2
def apply_mask(frame, mask):
"""Apply binary mask to frame, return in-place masked image."""
return cv2.bitwise_and(frame, frame, mask=mask)
Mask and frame must be the same size, so pixels remain as-is where mask is 1
and are set to zero where mask pixel is 0
.
And for C++
it's a little bit different:
cv::Mat inFrame; // Original (non-empty) image
cv::Mat mask; // Original (non-empty) mask
// ...
cv::Mat outFrame; // Result output
inFrame.copyTo(outFrame, mask);
VBA uses a garbage collector which is implemented by reference counting.
There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook
creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.
Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)
For a quick, neat, visual check, try this:
for col in df.columns:
print col
Similar setup here and looks like it was just a bug in my code. At the start of my app I looked for the offending URL and this worked: echo '<html>test</html>'; exit();
In my case, turns out the problem was an uninitialized variable that only failed under peculiar circumstances.
My sugession is Foxit PDF Reader which is very helpful to do important text editing work on pdf file.
There are a lot of solutions. For example you can use at()
method.
*I assumed that you a looking for equivalent to []
operator.
this is what I have done. Check it out, hope it can help.
#!/bin/bash
#
# So something to show.
echo "UNO" > UNO.txt
echo "DOS" > DOS.txt
#
# Initialize Pid List
dPidLst=""
#
# Generate background processes
tail -f UNO.txt&
dPidLst="$dPidLst $!"
tail -f DOS.txt&
dPidLst="$dPidLst $!"
#
# Report process IDs
echo PID=$$
echo dPidLst=$dPidLst
#
# Show process on current shell
ps -f
#
# Start killing background processes from list
for dPid in $dPidLst
do
echo killing $dPid. Process is still there.
ps | grep $dPid
kill $dPid
ps | grep $dPid
echo Just ran "'"ps"'" command, $dPid must not show again.
done
Then just run it as: ./bgkill.sh
with proper permissions of course
root@umsstd22 [P]:~# ./bgkill.sh
PID=23757
dPidLst= 23758 23759
UNO
DOS
UID PID PPID C STIME TTY TIME CMD
root 3937 3935 0 11:07 pts/5 00:00:00 -bash
root 23757 3937 0 11:55 pts/5 00:00:00 /bin/bash ./bgkill.sh
root 23758 23757 0 11:55 pts/5 00:00:00 tail -f UNO.txt
root 23759 23757 0 11:55 pts/5 00:00:00 tail -f DOS.txt
root 23760 23757 0 11:55 pts/5 00:00:00 ps -f
killing 23758. Process is still there.
23758 pts/5 00:00:00 tail
./bgkill.sh: line 24: 23758 Terminated tail -f UNO.txt
Just ran 'ps' command, 23758 must not show again.
killing 23759. Process is still there.
23759 pts/5 00:00:00 tail
./bgkill.sh: line 24: 23759 Terminated tail -f DOS.txt
Just ran 'ps' command, 23759 must not show again.
root@umsstd22 [P]:~# ps -f
UID PID PPID C STIME TTY TIME CMD
root 3937 3935 0 11:07 pts/5 00:00:00 -bash
root 24200 3937 0 11:56 pts/5 00:00:00 ps -f
for ( i = 0; i < total.length; i++ ); // remove this
{
if (total[i]!=0)
System.out.println( "Letter" + (char)( 'a' + i) + " count =" + total[i]);
}
The for loop loops until i=26
(where 26 is total.length
) and then your if
is executed, going over the bounds of the array. Remove the ;
at the end of the for
loop.
For +300k concurrent connection:
Set these variables in /etc/sysctl.conf
:
fs.file-max = 10000000
fs.nr_open = 10000000
Also, change these variables in /etc/security/limits.conf
:
* soft nofile 10000000
* hard nofile 10000000
root soft nofile 10000000
root hard nofile 10000000
And finally, increase TCP buffers in /etc/sysctl.conf
, too:
net.ipv4.tcp_mem = 786432 1697152 1945728
net.ipv4.tcp_rmem = 4096 4096 16777216
net.ipv4.tcp_wmem = 4096 4096 16777216
for more information please refer to this.
In my case there was another directory within my workspace, having the same jar file as the one in my project. I hadn't created that directory or anything in it. It was created by Eclipse I believe. I just erased that directory and it just runs ok.
Your XML is slightly wrong, you need to add any class exclusions within an excludes parent field, so your above configuration should look like the following as per the Jacoco docs
<configuration>
<excludes>
<exclude>**/*Config.*</exclude>
<exclude>**/*Dev.*</exclude>
</excludes>
</configuration>
The values of the exclude fields should be class paths (not package names) of the compiled classes relative to the directory target/classes/ using the standard wildcard syntax
* Match zero or more characters
** Match zero or more directories
? Match a single character
You may also exclude a package and all of its children/subpackages this way:
<exclude>some/package/**/*</exclude>
This will exclude every class in some.package
, as well as any children. For example, some.package.child
wouldn't be included in the reports either.
I have tested and my report goal reports on a reduced number of classes using the above.
If you are then pushing this report into Sonar, you will then need to tell Sonar to exclude these classes in the display which can be done in the Sonar settings
Settings > General Settings > Exclusions > Code Coverage
Sonar Docs explains it a bit more
Running your command above
mvn clean verify
Will show the classes have been excluded
No exclusions
[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 37 classes
With exclusions
[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 34 classes
Hope this helps
Python 3 has a different and simpler syntax for calling parent method.
If Foo
class inherits from Bar
, then from Bar.__init__
can be invoked from Foo
via super().__init__()
:
class Foo(Bar):
def __init__(self, *args, **kwargs):
# invoke Bar.__init__
super().__init__(*args, **kwargs)
Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.
This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
strXls, True, "temp!"
To save as data:
From StoryBoard, if you want to save "image" data on the imageView of MainStoryBoard, following codes will work.
let image = UIImagePNGRepresentation(imageView.image!) as NSData?
To load "image" to imageView: Look at exclamation point "!", "?" closely whether that is quite same as this one.
imageView.image = UIImage(data: image as! Data)
"NSData" type is converted into "Data" type automatically during this process.
No need to worry for incrementing/decrementing numbers using Javascript. Now HTML itself provides an easy way for it.
<input type="number" value="50">
It is that simple.The problem is that it works fine only in some browsers.Mozilla has not yet supported this feature.
For testing how to insert the double quotes in MySQL using the terminal, you can use the following way:
TableName(Name,DString) - > Schema
insert into TableName values("Name","My QQDoubleQuotedStringQQ")
After inserting the value you can update the value in the database with double quotes or single quotes:
update table TableName replace(Dstring, "QQ", "\"")
Actually, pretty much anywhere in typescript, passing a value to a function with a specified type will work as desired as long as the type being passed is compatible.
That being said, the following works...
fetch(`http://swapi.co/api/people/1/`)
.then(res => res.json())
.then((res: Actor) => {
// res is now an Actor
});
I wanted to wrap all of my http calls in a reusable class - which means I needed some way for the client to process the response in its desired form. To support this, I accept a callback lambda as a parameter to my wrapper method. The lambda declaration accepts an any type as shown here...
callBack: (response: any) => void
But in use the caller can pass a lambda that specifies the desired return type. I modified my code from above like this...
fetch(`http://swapi.co/api/people/1/`)
.then(res => res.json())
.then(res => {
if (callback) {
callback(res); // Client receives the response as desired type.
}
});
So that a client can call it with a callback like...
(response: IApigeeResponse) => {
// Process response as an IApigeeResponse
}
If you want to build DOM you can use jsdom.
There's also cheerio, it has the jQuery interface and it's a lot faster than older versions of jsdom, although these days they are similar in performance.
You might wanna have a look at htmlparser2, which is a streaming parser, and according to its benchmark, it seems to be faster than others, and no DOM by default. It can also produce a DOM, as it is also bundled with a handler that creates a DOM. This is the parser that is used by cheerio.
parse5 also looks like a good solution. It's fairly active (11 days since the last commit as of this update), WHATWG-compliant, and is used in jsdom, Angular, and Polymer.
And if you want to parse HTML for web scraping, you can use YQL1. There is a node module for it. YQL I think would be the best solution if your HTML is from a static website, since you are relying on a service, not your own code and processing power. Though note that it won't work if the page is disallowed by the robot.txt of the website, YQL won't work with it.
If the website you're trying to scrape is dynamic then you should be using a headless browser like phantomjs. Also have a look at casperjs, if you're considering phantomjs. And you can control casperjs from node with SpookyJS.
Beside phantomjs there's zombiejs. Unlike phantomjs that cannot be embedded in nodejs, zombiejs is just a node module.
There's a nettuts+ toturial for the latter solutions.
1 Since Aug. 2014, YUI library, which is a requirement for YQL, is no longer actively maintained, source
I'd suggest using TradeKing's developer API. It is very good and free to use. All that is required is that you have an account with them and to my knowledge you don't have to carry a balance ... only to be registered.
Answered this just to emphasize @rblarsen comment on question :
You don't need the style tags in the CSS-file
If you remove the style tag from your css file it will work.
Declare systemStatus in an outer scope and assign it in an onload handler.
systemStatus = null;
function onloadHandler(evt) {
systemStatus = document.getElementById("....");
}
Or if you don't want the onload handler, put your script tag at the bottom of your HTML.
Are all the modifications to file.py
in branch2
in their own commits, separate from modifications to other files? If so, you can simply cherry-pick
the changes over:
git checkout branch1
git cherry-pick <commit-with-changes-to-file.py>
Otherwise, merge
does not operate over individual paths...you might as well just create a git diff
patch of file.py
changes from branch2
and git apply
them to branch1
:
git checkout branch2
git diff <base-commit-before-changes-to-file.py> -- file.py > my.patch
git checkout branch1
git apply my.patch
Another option if using drupal is simply to add the css style that you want to use. that way it does not strip out the style or class name.
so in my case under the css tab in drupal 7 simply add something like
facebook=span.icon-facebook2
also check that font-styles button is enabled
Since the OP was asking for using a custom compare function (and this is what led me to this question as well), I want to give a solid answer here:
Generally, you want to use the built-in sorted()
function which takes a custom comparator as its parameter. We need to pay attention to the fact that in Python 3 the parameter name and semantics have changed.
When providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks):
< 0
) when the left item should be sorted before the right item> 0
) when the left item should be sorted after the right item0
when both the left and the right item have the same weight and should be ordered "equally" without precedenceIn the particular case of the OP's question, the following custom compare function can be used:
def compare(item1, item2):
return fitness(item1) - fitness(item2)
Using the minus operation is a nifty trick because it yields to positive values when the weight of left item1
is bigger than the weight of the right item2
. Hence item1
will be sorted after item2
.
If you want to reverse the sort order, simply reverse the subtraction: return fitness(item2) - fitness(item1)
sorted(mylist, cmp=compare)
or:
sorted(mylist, cmp=lambda item1, item2: fitness(item1) - fitness(item2))
from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(compare))
or:
from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(lambda item1, item2: fitness(item1) - fitness(item2)))
I am using a very simple solution. Here my code:
imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.getLayoutParams().height = imageView.getLayoutParams().width;
imageView.setMinimumHeight(imageView.getLayoutParams().width);
My pictures are added dynamically in a gridview. When you make these settings to the imageview, the picture can be automatically displayed in 1:1 ratio.
Let's say the name was used in a variable, $Name
.
You then run this query:
INSERT INTO Students VALUES ( '$Name' )
The code is mistakenly placing anything the user supplied as the variable.
You wanted the SQL to be:
INSERT INTO Students VALUES ( 'Robert Tables` )
But a clever user can supply whatever they want:
INSERT INTO Students VALUES ( 'Robert'); DROP TABLE Students; --' )
What you get is:
INSERT INTO Students VALUES ( 'Robert' ); DROP TABLE STUDENTS; --' )
The --
only comments the remainder of the line.
2018 here. Use background-size with percentage.
SHEET:
This assumes a single row of sprites. The width of your sheet should be a number that is evenly divisible by 100 + width of one sprite. If you have 30 sprites that are 108x108 px, then add extra blank space to the end to make the final width 5508px (50*108 + 108).
CSS:
.icon{
height: 30px; /* Set this to anything. It will scale. */
width: 30px; /* Match height. This assumes square sprites. */
background:url(<mysheeturl>);
background-size: 5100% 100%; /* 5100% because 51 sprites. */
}
/* Each image increases by 2% because we used 50+1 sprites.
If we had used 20+1 sprites then % increase would be 5%. */
.first_image{
background-position: 0% 0;
}
.ninth_image{
background-position: 16% 0; /* (9-1) x 2 = 16 */
}
HTML:
<div class ="icon first_image"></div>
<div class ="icon ninth_image"></div>
Another alternative
for(String serverId : serverIds) {
sb.append(",");
sb.append(serverId);
}
sb.deleteCharAt(0);
From the man page (for bash ls):
Sort entries alphabetically if none of -cftuSUX nor --sort.
I could be wrong, but I'm pretty sure that the "interrupt kernel" button just sends a SIGINT signal to the code that you're currently running (this idea is supported by Fernando's comment here), which is the same thing that hitting CTRL+C would do. Some processes within python handle SIGINTs more abruptly than others.
If you desperately need to stop something that is running in iPython Notebook and you started iPython Notebook from a terminal, you can hit CTRL+C twice in that terminal to interrupt the entire iPython Notebook server. This will stop iPython Notebook alltogether, which means it won't be possible to restart or save your work, so this is obviously not a great solution (you need to hit CTRL+C twice because it's a safety feature so that people don't do it by accident). In case of emergency, however, it generally kills the process more quickly than the "interrupt kernel" button.
This is a variance of need to reset body to original content. It doesn't deal with a form but I feel it might be of some use. If the original content was a ton of html, it is very difficult to string out the html and store it to a variable. Javascript does not take kindly to the line breaks that VS 2015/whatever allows. So I store original ton of html in default modal like this on page load:
var stylesString = $('#DefaultModal .modal-body').html();
Which allows me to to reuse this content when original default button for modal is pressed (there are other buttons that show other content in same modal).
$("#btnStyles").click(function () {
//pass the data in the modal body adding html elements
$('#DefaultModal .modal-body').html(stylesString);
$('#DefaultModal').modal('show');
})
If I put an alert for the styleString variable it would have an endless string of all the html with no breaks but does it for me and keeps it out of VS editor.
Here is how it looks in Visual Studio inside default modal. Saved in the string variable whether automatic (.html) or by hand in VS, it would be one big line:
<div class="modal-body" id="modalbody">
<div class="whatdays"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">All Styles</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/ballroom.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Ballroom</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/blues.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Blues</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/contra.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Contra</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/countrywestern.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Country</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/english-country.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">English Country</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/israeli.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Israeli</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/lindyhop.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Lindy Hop/Swing</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/miscvariety.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Misch/Variety</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/neo-square.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Neo-Square</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/polka.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Polka</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/salsa.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Salsa</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/scottish.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Scottish</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/square.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Square</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/tango.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Tango</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/waltz.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Waltz</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/wcswing.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">WCS</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/zyedeco-gator.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Zydeco/Cajun</span></div>
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
It the element has two xpath. Then you can write two xpaths like below:
xpath1
| xpath2
Eg:
//input[@name="username"] | //input[@id="wm_login-username"]
Just returning response()->json($promotion)
won't solve the issue in this question. $promotion
is an Eloquent object, which Laravel will automatically json_encode for the response. The json encoding is failing because of the img
property, which is a PHP stream resource, and cannot be encoded.
Whatever you return from your controller, Laravel is going to attempt to convert to a string. When you return an object, the object's __toString()
magic method will be invoked to make the conversion.
Therefore, when you just return $promotion
from your controller action, Laravel is going to call __toString()
on it to convert it to a string to display.
On the Model
, __toString()
calls toJson()
, which returns the result of json_encode
. Therefore, json_encode
is returning false
, meaning it is running into an error.
Your dd
shows that your img
attribute is a stream resource
. json_encode
cannot encode a resource
, so this is probably causing the failure. You should add your img
attribute to the $hidden
property to remove it from the json_encode
.
class Promotion extends Model
{
protected $hidden = ['img'];
// rest of class
}
I like using the ggplot2
for this sort of thing:
df$Date <- as.Date( df$Date, '%m/%d/%Y')
require(ggplot2)
ggplot( data = df, aes( Date, Visits )) + geom_line()
&
is bitwise.
&&
is logical.
&
evaluates both sides of the operation.
&&
evaluates the left side of the operation, if it's true
, it continues and evaluates the right side.
I 'm using this :
function getFirstWord(str) {
let spaceIndex = str.indexOf(' ');
return spaceIndex === -1 ? str : str.substr(0, spaceIndex);
};
The tick_params
method is very useful for stuff like this. This code turns off major and minor ticks and removes the labels from the x-axis.
from matplotlib import pyplot as plt
plt.plot(range(10))
plt.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False) # labels along the bottom edge are off
plt.show()
plt.savefig('plot')
plt.clf()
No
Shortish Answer:Only if the other application is designed to allow it, by providing components for you to add into your own application.
I think that's up to you to show that dialog for choosing. For Gallery you'll use that code, and for Camera try this.
string[] MyArray = new string[] { "A", "B" };
MyArray = new List<string>(MyArray) { "C" }.ToArray();
//MyArray = ["A", "B", "C"]
Here is a Swift 3 version of Anth0's answer. I'm posting it here to help any swift developers in wanting to take advantage of his great answer! I took the liberty of adding a return key type of "Next" when you set the associated object.
extension UITextField {
@nonobjc static var NextHashKey: UniChar = 0
var nextTextField: UITextField? {
get {
return objc_getAssociatedObject(self,
&UITextField.NextHashKey) as? UITextField
}
set(next) {
self.returnKeyType = UIReturnKeyType.next
objc_setAssociatedObject(self,
&UITextField.NextHashKey,next,.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
Here is another extension that shows a possibility of using the above code to cycle through a list of UITextFields.
extension UIViewController: UITextFieldDelegate {
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard let next = textField.nextTextField else {
textField.resignFirstResponder()
return true
}
next.becomeFirstResponder()
return false
}
}
And then in your ViewController or wherever, you can setup your textfields like so...
@IBOutlet fileprivate weak var textfield1: UITextField!
@IBOutlet fileprivate weak var textfield2: UITextField!
@IBOutlet fileprivate weak var textfield3: UITextField!
...
[textfield1, textfield2, textfield3].forEach{ $0?.delegate = self }
textfield1.nextTextField = textfield2
textfield2.nextTextField = textfield3
// We don't assign a nextTextField to textfield3 because we want
// textfield3 to be the last one and resignFirstResponder when
// the return button on the soft keyboard is tapped.
I found Green plugin very simple to use and to generate class diagram from source code. Give it a try :). Just copy the plugin to your plugin dir.
This is an easy way to create custom events and raise them. You create a delegate and an event in the class you are throwing from. Then subscribe to the event from another part of your code. You have already got a custom event argument class so you can build on that to make other event argument classes. N.B: I have not compiled this code.
public partial class Form1 : Form
{
private TestClass _testClass;
public Form1()
{
InitializeComponent();
_testClass = new TestClass();
_testClass.OnUpdateStatus += new TestClass.StatusUpdateHandler(UpdateStatus);
}
private void UpdateStatus(object sender, ProgressEventArgs e)
{
SetStatus(e.Status);
}
private void SetStatus(string status)
{
label1.Text = status;
}
private void button1_Click_1(object sender, EventArgs e)
{
TestClass.Func();
}
}
public class TestClass
{
public delegate void StatusUpdateHandler(object sender, ProgressEventArgs e);
public event StatusUpdateHandler OnUpdateStatus;
public static void Func()
{
//time consuming code
UpdateStatus(status);
// time consuming code
UpdateStatus(status);
}
private void UpdateStatus(string status)
{
// Make sure someone is listening to event
if (OnUpdateStatus == null) return;
ProgressEventArgs args = new ProgressEventArgs(status);
OnUpdateStatus(this, args);
}
}
public class ProgressEventArgs : EventArgs
{
public string Status { get; private set; }
public ProgressEventArgs(string status)
{
Status = status;
}
}
To expand a little further, here are some common examples. Starting with:
const [theArray, setTheArray] = useState(initialArray);
const [theObject, setTheObject] = useState(initialObject);
Push element at end of array
setTheArray(prevArray => [...prevArray, newValue])
Push/update element at end of object
setTheObject(prevState => ({ ...prevState, currentOrNewKey: newValue}));
Push/update element at end of array of objects
setTheArray(prevState => [...prevState, {currentOrNewKey: newValue}]);
Push element at end of object of arrays
let specificArrayInObject = theObject.array.slice();
specificArrayInObject.push(newValue);
const newObj = { ...theObject, [event.target.name]: specificArrayInObject };
theObject(newObj);
Here are some working examples too. https://codesandbox.io/s/reacthooks-push-r991u
Go to your image in windows, then press ctrl + c OR Right click and Copy
Go to Your res Folder And choose One of the folders(eg. MDPI, HDPI..) and press ctrl + v OR right click it and Paste
I don't know any native cmdlet in powershell but you can use com object instead:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()
you can create a powershell script save as set-shortcut.ps1 in your $pwd
param ( [string]$SourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()
and call it like this
Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"
If you want to pass arguments to the target exe, it can be done by:
#Set the additional parameters for the shortcut
$Shortcut.Arguments = "/argument=value"
before $Shortcut.Save().
For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.
param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()
This works but password length should be exactly 8
. This is simple and requires pyDes.
from pyDes import *
def encode(data,password):
k = des(password, CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.encrypt(data)
return d
def decode(data,password):
k = des(password, CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.decrypt(data)
return d
x = encode('John Doe', 'mypass12')
y = decode(x,'mypass12')
print x
print y
OUTPUT:
³.\Þ\åS¾+æÅ`;Ê
John Doe
You can try max-height: 70px; See if that works.
One liner using Set
var things = new Object();_x000D_
_x000D_
things.thing = new Array();_x000D_
_x000D_
things.thing.push({place:"here",name:"stuff"});_x000D_
things.thing.push({place:"there",name:"morestuff"});_x000D_
things.thing.push({place:"there",name:"morestuff"});_x000D_
_x000D_
// assign things.thing to myData for brevity_x000D_
var myData = things.thing;_x000D_
_x000D_
things.thing = Array.from(new Set(myData.map(JSON.stringify))).map(JSON.parse);_x000D_
_x000D_
console.log(things.thing)
_x000D_
Explanation:
new Set(myData.map(JSON.stringify))
creates a Set object using the stringified myData elements. A lot of great editors have come out since my original answer. I currently use the following text editors: Sublime Text 3 (Mac/Windows), Visual Studio Code (Mac/Windows) and Atom (Mac/Windows). I also use the following IDEs: Visual Studio 2015 (Windows/Paid & Free Versions) and Jetrbrains WebStorm (Windows/Paid, tried the demo and liked it).
My preference is using Sublime Text 3.
Microsoft Web Matrix and Dreamweaver are great.
Visual Studio and Expression Web are also great but may be overkill for you.
For just plain text editors, Sublime Text 2 is really cool
You could use hidden input tags. I get no validation errors at w3.org with this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='en' xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta content="text/html;charset=UTF-8" http-equiv="content-type" />
<title>Hello</title>
</head>
<body>
<div>
<a class="article" href="link/for/non-js-users.html">
<input style="display: none" name="articleid" type="hidden" value="5" />
</a>
</div>
</body>
</html>
With jQuery you'd get the article ID with something like (not tested):
$('.article input[name=articleid]').val();
But I'd recommend HTML5 if that is an option.
I found that in my code when I used a ration or percentage for line-height line-height;1.5;
My page would scale in such a way that lower case font and upper case font would take up different page heights (I.E. All caps took more room than all lower). Normally I think this looks better, but I had to go to a fixed height line-height:24px;
so that I could predict exactly how many pixels each page would take with a given number of lines.
An understanding of the Iterator pattern will be helpful for you. I recommend reading the same.
At a high level the iterator pattern can be used to provide a standard way of iterating through collections of any type. We have 3 participants in the iterator pattern, the actual collection (client), the aggregator and the iterator. The aggregate is an interface/abstract class that has a method that returns an iterator. Iterator is an interface/abstract class that has methods allowing us to iterate through a collection.
In order to implement the pattern we first need to implement an iterator to produce a concrete that can iterate over the concerned collection (client) Then the collection (client) implements the aggregator to return an instance of the above iterator.
So basically in c#, IEnumerable is the abstract aggregate and IEnumerator is the abstract Iterator. IEnumerable has a single method GetEnumerator that is responsible for creating an instance of IEnumerator of the desired type. Collections like Lists implement the IEnumerable.
Example.
Lets suppose that we have a method getPermutations(inputString)
that returns all the permutations of a string and that the method returns an instance of IEnumerable<string>
In order to count the number of permutations we could do something like the below.
int count = 0;
var permutations = perm.getPermutations(inputString);
foreach (string permutation in permutations)
{
count++;
}
The c# compiler more or less converts the above to
using (var permutationIterator = perm.getPermutations(input).GetEnumerator())
{
while (permutationIterator.MoveNext())
{
count++;
}
}
If you have any questions please don't hesitate to ask.
The PyPA recommended tool for installing and managing Python packages is pip
. pip
is included with Python 3.4 (PEP 453), but for older versions here's how to install it (on Windows, using Python 3.3):
Download https://bootstrap.pypa.io/get-pip.py
>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...
Sample usage:
>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...
In your case it would be this (it appears that pip
caches independent of Python version):
C:\Python27>python.exe \code\Python\get-pip.py
Requirement already up-to-date: pip in c:\python27\lib\site-packages
Collecting wheel
Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB)
100% |################################| 69kB 255kB/s
Installing collected packages: wheel
Successfully installed wheel-0.29.0
C:\Python27>cd Scripts
C:\Python27\Scripts>pip install twilio
Collecting twilio
Using cached twilio-5.3.0.tar.gz
Collecting httplib2>=0.7 (from twilio)
Using cached httplib2-0.9.2.tar.gz
Collecting six (from twilio)
Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pytz (from twilio)
Using cached pytz-2015.7-py2.py3-none-any.whl
Building wheels for collected packages: twilio, httplib2
Running setup.py bdist_wheel for twilio ... done
Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e0\f2\a7\c57f6d153c440b93bd24c1243123f276dcacbf43cc43b7f906
Running setup.py bdist_wheel for httplib2 ... done
Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e1\a3\05\e66aad1380335ee0a823c8f1b9006efa577236a24b3cb1eade
Successfully built twilio httplib2
Installing collected packages: httplib2, six, pytz, twilio
Successfully installed httplib2-0.9.2 pytz-2015.7 six-1.10.0 twilio-5.3.0
You likely forgot to #include <stdlib.h>
Below you have some VALID html5 example document. The type
attribute in script
tag is not mandatory in HTML5.
You use jquery by $
charater. Put libraries (like jquery) in <head>
tag - but your script put allways at the bottom of document (<body>
tag) - due this you will be sure that all libraries and html document will be loaded when your script execution starts. You can also use src
attribute in bottom script tag to include you script file instead of putting direct js code like above.
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Example</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<div>Im the content</div>_x000D_
_x000D_
<script>_x000D_
alert( $('div').text() ); // show message with div content_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
There are many good answers here but you should avoid at all cost to pass untrusted variables to subprocess using shell=True
as this is a security risk. The variables can escape to the shell and run arbitrary commands! If you just can't avoid it at least use python3's shlex.quote()
to escape the string (if you have multiple space-separated arguments, quote each split instead of the full string).
shell=False
is always the default where you pass an argument array.
Now the safe solutions...
Change your own process's environment - the new environment will apply to python itself and all subprocesses.
os.environ['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)
Make a copy of the environment and pass is to the childen. You have total control over the children environment and won't affect python's own environment.
myenv = os.environ.copy()
myenv['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command, env=myenv)
Unix only: Execute env
to set the environment variable. More cumbersome if you have many variables to modify and not portabe, but like #2 you retain full control over python and children environments.
command = ['env', 'LD_LIBRARY_PATH=my_path', 'sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)
Of course if var1
contain multiple space-separated argument they will now be passed as a single argument with spaces. To retain original behavior with shell=True
you must compose a command array that contain the splitted string:
command = ['sqsub', '-np'] + var1.split() + ['/homedir/anotherdir/executable']
Here's a simple function using a regexp that imitates the a
tag behavior.
Pros
Cons
-
function getLocation(href) {
var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
return match && {
href: href,
protocol: match[1],
host: match[2],
hostname: match[3],
port: match[4],
pathname: match[5],
search: match[6],
hash: match[7]
}
}
-
getLocation("http://example.com/");
/*
{
"protocol": "http:",
"host": "example.com",
"hostname": "example.com",
"port": undefined,
"pathname": "/"
"search": "",
"hash": "",
}
*/
getLocation("http://example.com:3000/pathname/?search=test#hash");
/*
{
"protocol": "http:",
"host": "example.com:3000",
"hostname": "example.com",
"port": "3000",
"pathname": "/pathname/",
"search": "?search=test",
"hash": "#hash"
}
*/
EDIT:
Here's a breakdown of the regular expression
var reURLInformation = new RegExp([
'^(https?:)//', // protocol
'(([^:/?#]*)(?::([0-9]+))?)', // host (hostname and port)
'(/{0,1}[^?#]*)', // pathname
'(\\?[^#]*|)', // search
'(#.*|)$' // hash
].join(''));
var match = href.match(reURLInformation);
Create an alias for gcc with your favorite includes.
alias mygcc='gcc -I /whatever/'
Warning: Use the below steps at your own risk. You may receive different results as indicated in the comments. Please exercise caution and have a full backup prior to doing this.
Below is a list of steps used to solve the issue:
Remove Docker (this won't delete images, containers, volumes, or customized configuration files):
sudo apt-get purge docker-engine
Remove the Docker apt key:
sudo apt-key del 58118E89F3A912897C070ADBF76221572C52609D
Delete the docker.list file:
sudo rm /etc/apt/sources.list.d/docker.list
Manually delete apt cache files:
sudo rm /var/lib/apt/lists/apt.dockerproject.org_repo_dists_ubuntu-xenial_*
Delete apt-transport-https and ca-certificates:
sudo apt-get purge apt-transport-https ca-certificates
Clean apt and perform autoremove:
sudo apt-get clean && sudo apt-get autoremove
Reboot Ubuntu:
sudo reboot
Run apt-get update:
sudo apt-get update
Install apt-transport-https and ca-certificates again:
sudo apt-get install apt-transport-https ca-certificates
Add the apt key:
> sudo apt-key adv \
--keyserver hkp://ha.pool.sks-keyservers.net:80 \
--recv-keys 58118E89F3A912897C070ADBF76221572C52609D
> echo "deb https://apt.dockerproject.org/repo ubuntu-xenial main" |
sudo tee /etc/apt/sources.list.d/docker.list
> sudo apt-get update
> sudo apt-get install docker-engine
Granted, there are plenty of variables and your results may vary. However, these steps cover as many areas as possible to ensure potential problem spots are scrubbed so that the likelihood of success is higher.
Update 7/6/2017
It appears newer versions of Docker are using a different installation process which should eliminate many of these problems. Be sure to check out https://docs.docker.com/engine/installation/linux/ubuntu/.
Why do we use:
1) cin.ignore
2) cin.clear
?
Simply:
1) To ignore (extract and discard) values that we don't want on the stream
2) To clear the internal state of stream. After using cin.clear internal state is set again back to goodbit, which means that there are no 'errors'.
Long version:
If something is put on 'stream' (cin) then it must be taken from there. By 'taken' we mean 'used', 'removed', 'extracted' from stream. Stream has a flow. The data is flowing on cin like water on stream. You simply cannot stop the flow of water ;)
Look at the example:
string name; //line 1
cout << "Give me your name and surname:"<<endl;//line 2
cin >> name;//line 3
int age;//line 4
cout << "Give me your age:" <<endl;//line 5
cin >> age;//line 6
What happens if the user answers: "Arkadiusz Wlodarczyk" for first question?
Run the program to see for yourself.
You will see on console "Arkadiusz" but program won't ask you for 'age'. It will just finish immediately right after printing "Arkadiusz".
And "Wlodarczyk" is not shown. It seems like if it was gone (?)*
What happened? ;-)
Because there is a space between "Arkadiusz" and "Wlodarczyk".
"space" character between the name and surname is a sign for computer that there are two variables waiting to be extracted on 'input' stream.
The computer thinks that you are tying to send to input more than one variable. That "space" sign is a sign for him to interpret it that way.
So computer assigns "Arkadiusz" to 'name' (2) and because you put more than one string on stream (input) computer will try to assign value "Wlodarczyk" to variable 'age' (!). The user won't have a chance to put anything on the 'cin' in line 6 because that instruction was already executed(!). Why? Because there was still something left on stream. And as I said earlier stream is in a flow so everything must be removed from it as soon as possible. And the possibility came when computer saw instruction cin >> age;
Computer doesn't know that you created a variable that stores age of somebody (line 4). 'age' is merely a label. For computer 'age' could be as well called: 'afsfasgfsagasggas' and it would be the same. For him it's just a variable that he will try to assign "Wlodarczyk" to because you ordered/instructed computer to do so in line (6).
It's wrong to do so, but hey it's you who did it! It's your fault! Well, maybe user, but still...
All right all right. But how to fix it?!
Let's try to play with that example a bit before we fix it properly to learn a few more interesting things :-)
I prefer to make an approach where we understand things. Fixing something without knowledge how we did it doesn't give satisfaction, don't you think? :)
string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate(); //new line is here :-)
After invoking above code you will notice that the state of your stream (cin) is equal to 4 (line 7). Which means its internal state is no longer equal to goodbit. Something is messed up. It's pretty obvious, isn't it? You tried to assign string type value ("Wlodarczyk") to int type variable 'age'. Types doesn't match. It's time to inform that something is wrong. And computer does it by changing internal state of stream. It's like: "You f**** up man, fix me please. I inform you 'kindly' ;-)"
You simply cannot use 'cin' (stream) anymore. It's stuck. Like if you had put big wood logs on water stream. You must fix it before you can use it. Data (water) cannot be obtained from that stream(cin) anymore because log of wood (internal state) doesn't allow you to do so.
Oh so if there is an obstacle (wood logs) we can just remove it using tools that is made to do so?
Yes!
internal state of cin set to 4 is like an alarm that is howling and making noise.
cin.clear clears the state back to normal (goodbit). It's like if you had come and silenced the alarm. You just put it off. You know something happened so you say: "It's OK to stop making noise, I know something is wrong already, shut up (clear)".
All right let's do so! Let's use cin.clear().
Invoke below code using "Arkadiusz Wlodarczyk" as first input:
string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl;
cin.clear(); //new line is here :-)
cout << cin.rdstate()<< endl; //new line is here :-)
We can surely see after executing above code that the state is equal to goodbit.
Great so the problem is solved?
Invoke below code using "Arkadiusz Wlodarczyk" as first input:
string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl;;
cin.clear();
cout << cin.rdstate() << endl;
cin >> age;//new line is here :-)
Even tho the state is set to goodbit after line 9 the user is not asked for "age". The program stops.
WHY?!
Oh man... You've just put off alarm, what about the wood log inside a water?* Go back to text where we talked about "Wlodarczyk" how it supposedly was gone.
You need to remove "Wlodarczyk" that piece of wood from stream. Turning off alarms doesn't solve the problem at all. You've just silenced it and you think the problem is gone? ;)
So it's time for another tool:
cin.ignore can be compared to a special truck with ropes that comes and removes the wood logs that got the stream stuck. It clears the problem the user of your program created.
So could we use it even before making the alarm goes off?
Yes:
string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;
The "Wlodarczyk" is gonna be removed before making the noise in line 7.
What is 10000 and '\n'?
It says remove 10000 characters (just in case) until '\n' is met (ENTER). BTW It can be done better using numeric_limits but it's not the topic of this answer.
So the main cause of problem is gone before noise was made...
Why do we need 'clear' then?
What if someone had asked for 'give me your age' question in line 6 for example: "twenty years old" instead of writing 20?
Types doesn't match again. Computer tries to assign string to int. And alarm starts. You don't have a chance to even react on situation like that. cin.ignore won't help you in case like that.
So we must use clear in case like that:
string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;
cin.clear();
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
But should you clear the state 'just in case'?
Of course not.
If something goes wrong (cin >> age;) instruction is gonna inform you about it by returning false.
So we can use conditional statement to check if the user put wrong type on the stream
int age;
if (cin >> age) //it's gonna return false if types doesn't match
cout << "You put integer";
else
cout << "You bad boy! it was supposed to be int";
All right so we can fix our initial problem like for example that:
string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
if (cin >> age)
cout << "Your age is equal to:" << endl;
else
{
cin.clear();
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
cout << "Give me your age name as string I dare you";
cin >> age;
}
Of course this can be improved by for example doing what you did in question using loop while.
BONUS:
You might be wondering. What about if I wanted to get name and surname in the same line from the user? Is it even possible using cin if cin interprets each value separated by "space" as different variable?
Sure, you can do it two ways:
1)
string name, surname;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin >> surname;
cout << "Hello, " << name << " " << surname << endl;
2) or by using getline function.
getline(cin, nameOfStringVariable);
and that's how to do it:
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
The second option might backfire you in case you use it after you use 'cin' before the getline.
Let's check it out:
a)
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endl;
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
If you put "20" as age you won't be asked for nameAndSurname.
But if you do it that way:
b)
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endll
everything is fine.
WHAT?!
Every time you put something on input (stream) you leave at the end white character which is ENTER ('\n') You have to somehow enter values to console. So it must happen if the data comes from user.
b) cin characteristics is that it ignores whitespace, so when you are reading in information from cin, the newline character '\n' doesn't matter. It gets ignored.
a) getline function gets the entire line up to the newline character ('\n'), and when the newline char is the first thing the getline function gets '\n', and that's all to get. You extract newline character that was left on stream by user who put "20" on stream in line 3.
So in order to fix it is to always invoke cin.ignore(); each time you use cin to get any value if you are ever going to use getline() inside your program.
So the proper code would be:
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cin.ignore(); // it ignores just enter without arguments being sent. it's same as cin.ignore(1, '\n')
cout << "Your age is" << age << endl;
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
I hope streams are more clear to you know.
Hah silence me please! :-)
Your answer suffers from the multiple-evaluation problem, so (eg)
macro( read_int(file1), read_int(file2) );
will do something unexpected and probably unwanted.
In Scala, a List inherits from Seq, but implements Product; here is the proper definition of List :
sealed abstract class List[+A] extends AbstractSeq[A] with Product with ...
[Note: the actual definition is a tad bit more complex, in order to fit in with and make use of Scala's very powerful collection framework.]
For floats:
float(filter(lambda x: x!=',', '1,234.52'))
# returns 1234.52
For ints:
int(filter(lambda x: x!=',', '1,234'))
# returns 1234
For Some Reason I could Not add Numbers(in string Format) to the DataGridView But This Worked For Me Hope it help someone!
//dataGridView1.Rows[RowCount].Cells[0].Value = FEString3;//This was not adding Stringed Numbers like "1","2","3"....
DataGridViewCell NewCell = new DataGridViewTextBoxCell();//Create New Cell
NewCell.Value = FEString3;//Set Cell Value
DataGridViewRow NewRow = new DataGridViewRow();//Create New Row
NewRow.Cells.Add(NewCell);//Add Cell to Row
dataGridView1.Rows.Add(NewRow);//Add Row To Datagrid
You should not be testing the private methods of your code in the first place. You should be testing the 'public interface' or API, the public things of your classes. The API are all the public methods you expose to outside callers.
The reason is that once you start testing the private methods and internals of your class you are coupling the implementation of your class (the private things) to your tests. This means that when you decide to change your implementation details you will also have to change your tests.
You should for this reason avoid using InternalsVisibleToAtrribute.
Here is a great talk by Ian Cooper which covers this subject: Ian Cooper: TDD, where did it all go wrong
I had used a CLGeocoder without adding a Core.Location Framework. Basically this error can mean multiple things. I hope this helps someone else.
I same thing happen with me, If your code is correct and then also give 405 error. this error due to some authorization problem. go to authorization menu and change to "Inherit auth from parent".
What do you mean by a long date type?
You can cast a long to a double:
double d = (double) 15552451L;
It would most likely process them sequentially (why not just test it). But you can also do this:
make a file called curlrequests.sh
put it in a file like thus:
curl http://example.com/?update_=1
curl http://example.com/?update_=3
curl http://example.com/?update_=234
curl http://example.com/?update_=65
save the file and make it executable with chmod
:
chmod +x curlrequests.sh
run your file:
./curlrequests.sh
or
/path/to/file/curlrequests.sh
As a side note, you can chain requests with &&
, like this:
curl http://example.com/?update_=1 && curl http://example.com/?update_=2 && curl http://example.com?update_=3`
And execute in parallel using &
:
curl http://example.com/?update_=1 & curl http://example.com/?update_=2 & curl http://example.com/?update_=3
This should solve your problem.
To answer your initial question: yes you can. Only Gecko and WebKit browsers support it currently though.
You just need to add link tags in your head:
<link rel="prefetch" href="pathto/font">
<link rel="prerender" href="pathto/page">
Do you mean like this?
<!-- ... --->
<td>
this text should be left justified
and this text should be right justified?
</td>
<!-- ... --->
If yes
<!-- ... --->
<td>
<p style="text-align: left;">this text should be left justified</p>
<p style="text-align: right;">and this text should be right justified?</p>
</td>
<!-- ... --->
Just to add the resource and complexity standpoint to the discussion. Since doing PUT/POST and PATCH for storing new resources and altering them, one should remember that the content transfer is an exact representation of the content that is stored and that is received by issuing a GET operation.
A multi-part message is often used as a savior but for simplicity reason and for more complex tasks, I prefer the idea of giving the content as a whole. It is self-explaining and it is simple.
And yes JSON is something crippling but in the end JSON itself is verbose. And the overhead of mapping to BASE64 is a way to small.
Using Multi-Part messages correctly one has to either dismantle the object to send, use a property path as the parameter name for automatic combination or will need to create another protocol/format to just express the payload.
Also liking the BSON approach, this is not that widely and easily supported as one would like it to be.
Basically, we just miss something here but embedding binary data as base64 is well established and way to go unless you really have identified the need to do the real binary transfer (which is hardly often the case).
Use Css Selector for this, or learn more about Css Selector just go here
https://www.w3schools.com/cssref/css_selectors.asp
#main_text > .title {
/* Style goes here */
}
#main_text .title {
/* Style goes here */
}
One way is by using document.getElementByID
, as below -
<body>
<h1>Adding 'a' and 'b'</h1>
a: <input type="number" name="a" id="a"><br> b: <input type="number" name="b" id="b"><br>
<button onclick="add(document.getElementById('a').value,document.getElementById('b').value)">Add</button>
<script>
function add(a, b) {
var sum = parseInt(a, 10) + parseInt(b, 10);
alert(sum);
}
</script>
</body>
_x000D_
public static void showPyramid(int level)
{
for(int i=0;i<level;i++)
{
for(int j=0;j<level-i-1;j++)
{
System.out.print(" ");
}
for(int k=level-i;k<=level;k++)
{
System.out.print("*");
}
for(int k=level-i;k<level;k++)
{
System.out.print("*");
}
for(int j=0;j<level-i;j++)
{
System.out.print(" ");
}
System.out.print("\n");
}
}
Output
*
***
*****
*******
*********
***********
This cannot be done from within the controller itself, but rather from your View. As I see it, you have two options:
Decorate your link with the "_blank" attribute (examples using HTML helper and straight HMTL syntax)
@Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank"})
<a href="@Url.Action("Action", "Controller")" target="_blank">Link Text</a>
Use Javascript to open a new window
window.open("Link URL")
Note that you do not need that many -l
s if you install glfw with the BUILD_SHARED_LIBS
option. (You can enable this option by running ccmake
first).
This way sudo make install
will install the shared library in /usr/local/lib/libglfw.so
.
You can then compile the example file with a simple:
g++ main.cpp -L /usr/local/lib/ -lglfw
Then do not forget to add /usr/local/lib/ to the search path for shared libraries before running your program. This can be done using:
export LD_LIBRARY_PATH=/usr/local/lib:${LD_LIBRARY_PATH}
And you can put that in your ~/.bashrc
so you don't have to type it all the time.
You could also use:
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
a = dict(one=1, two=2, three=3)
Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.
Based on @ganaraj 's answer, and @dnc253 's answer, I just made a simple "directive" for the tree structure having selecting, adding, deleting, and editing feature.
Jsfiddle: http://jsfiddle.net/yoshiokatsuneo/9dzsms7y/
HTML:
<script type="text/ng-template" id="tree_item_renderer.html">
<div class="node" ng-class="{selected: data.selected}" ng-click="select(data)">
<span ng-click="data.hide=!data.hide" style="display:inline-block; width:10px;">
<span ng-show="data.hide && data.nodes.length > 0" class="fa fa-caret-right">+</span>
<span ng-show="!data.hide && data.nodes.length > 0" class="fa fa-caret-down">-</span>
</span>
<span ng-show="!data.editting" ng-dblclick="edit($event)" >{{data.name}}</span>
<span ng-show="data.editting"><input ng-model="data.name" ng-blur="unedit()" ng-focus="f()"></input></span>
<button ng-click="add(data)">Add node</button>
<button ng-click="delete(data)" ng-show="data.parent">Delete node</button>
</div>
<ul ng-show="!data.hide" style="list-style-type: none; padding-left: 15px">
<li ng-repeat="data in data.nodes">
<recursive><sub-tree data="data"></sub-tree></recursive>
</li>
</ul>
</script>
<ul ng-app="Application" style="list-style-type: none; padding-left: 0">
<tree data='{name: "Node", nodes: [],show:true}'></tree>
</ul>
JavaScript:
angular.module("myApp",[]);
/* https://stackoverflow.com/a/14657310/1309218 */
angular.module("myApp").
directive("recursive", function($compile) {
return {
restrict: "EACM",
require: '^tree',
priority: 100000,
compile: function(tElement, tAttr) {
var contents = tElement.contents().remove();
var compiledContents;
return function(scope, iElement, iAttr) {
if(!compiledContents) {
compiledContents = $compile(contents);
}
compiledContents(scope,
function(clone) {
iElement.append(clone);
});
};
}
};
});
angular.module("myApp").
directive("subTree", function($timeout) {
return {
restrict: 'EA',
require: '^tree',
templateUrl: 'tree_item_renderer.html',
scope: {
data: '=',
},
link: function(scope, element, attrs, treeCtrl) {
scope.select = function(){
treeCtrl.select(scope.data);
};
scope.delete = function() {
scope.data.parent.nodes.splice(scope.data.parent.nodes.indexOf(scope.data), 1);
};
scope.add = function() {
var post = scope.data.nodes.length + 1;
var newName = scope.data.name + '-' + post;
scope.data.nodes.push({name: newName,nodes: [],show:true, parent: scope.data});
};
scope.edit = function(event){
scope.data.editting = true;
$timeout(function(){event.target.parentNode.querySelector('input').focus();});
};
scope.unedit = function(){
scope.data.editting = false;
};
}
};
});
angular.module("myApp").
directive("tree", function(){
return {
restrict: 'EA',
template: '<sub-tree data="data" root="data"></sub-tree>',
controller: function($scope){
this.select = function(data){
if($scope.selected){
$scope.selected.selected = false;
}
data.selected = true;
$scope.selected = data;
};
},
scope: {
data: '=',
}
}
});
Create a UNIQUE
constraint on your subs_email
column, if one does not already exist:
ALTER TABLE subs ADD UNIQUE (subs_email)
Use INSERT ... ON DUPLICATE KEY UPDATE
:
INSERT INTO subs
(subs_name, subs_email, subs_birthday)
VALUES
(?, ?, ?)
ON DUPLICATE KEY UPDATE
subs_name = VALUES(subs_name),
subs_birthday = VALUES(subs_birthday)
You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com
target.fadeOut(300, function(){ $(this).remove();});
or
$('#target_id').fadeOut(300, function(){ $(this).remove();});
Duplicate: How to "fadeOut" & "remove" a div in jQuery?
This is not actually a problem with the function being "void", but a problem with the function parameters. I think it's just g++ giving an unhelpful error message.
EDIT: As in the accepted answer, the fix is to use std::string
instead of just string
.
Iyap . Its work Case sensitive in data name data-x10
var variable = $('#myButton').data("x10");
// we get the value of custom data attribute
The error:
'\r'
: command not found
is caused by shell not able to recognise Windows-like CRLF line endings (0d 0a
) as it expects only LF
(0a
).
If you using Git on Windows, make sure you selected 'Checkout as-is' during setup. Then make sure that you run: git config --global core.autocrlf false
, so Git will not perform any conversions when checking out or committing text files.
dos2unix
If you're not using Git, you simply need to convert these affected files/scripts back into Unix-like line endings (LF), either by:
dos2unix ~/.bashrc
Note: The dos2unix
command is part of dos2unix
package.
tr
If you've Vim installed, the following command should correct the files:
ex +'bufdo! %! tr -d \\r' -scxa ~/.bash*
Useful alias: alias dos2unix="ex +'bufdo! %! tr -d \\\\r' -scxa"
.
tr
Here is the method by using tr
:
cat ~/.bashrc | tr -d '\r' > ~/.bashrc.fixed && mv -v ~/.bashrc.fixed ~/.bashrc
or:
tr -d '\r' < filename > new_filename
Note: The \r
is equivalent to \015
.
sed
You can try the following command:
sed -i'.bak' s/\r//g ~/.bash*
recode
The following aliases can be useful (which replaces dos2unix
command):
alias unix2dos='recode lat1:ibmpc'
alias dos2unix='recode ibmpc:lat1'
Source: Free Unix Tools (ssh, bash, etc) under Windows.
perl
The following perl
command can convert the file from DOS into Unix format:
perl -p -i.bak -e 's/\015//g' ~/.bash*
Source: stripping the ^M.
tofrodos
On Linux, like Ubuntu which doesn’t come standard with either dos2unix
or unix2dos
, you can install tofrodos
package (sudo apt-get install tofrodos
), and define the following aliases:
alias dos2unix=’fromdos’
alias unix2dos=’todos’
Then use in the same syntax as above.
If you're using Vagrant VM and this happens for provisioning script, try setting binary
option to true
:
# Shell provisioner, see: https://www.vagrantup.com/docs/provisioning/shell.html
config.vm.provision "shell" do |s|
s.binary = true # Replace Windows line endings with Unix line endings.
s.path = "script.sh"
end
This works for me :
$db = mysqli_connect('localhost', 'UserName', 'Password', 'DB_Name') or die('Not Connected');
mysqli_set_charset($db, 'utf8');
$sql = mysqli_query($db,"SELECT * FROM `mytable` WHERE city='c7'");
$sql = mysqli_fetch_assoc($sql);
$Checker = $sql['city'];
if ($Checker != null) {
echo 'Already exists';
} else {
echo 'Not found';
}
For complex splitting you could use a regex creating a match collection.
sometimes SECURITY issues prevent from asking for all the db's and you need to query one by one with the db prefix, for those cases i created this dynamic query
go
declare @Results table ([Name] nvarchar(max), [DataFileSizeMB] int, [LogFileSizeMB] int);
declare @QaQuery nvarchar(max)
declare @name nvarchar(max)
declare MY_CURSOR cursor
local static read_only forward_only
for
select name from master.dbo.sysdatabases where name not in ('master', 'tempdb', 'model', 'msdb', 'rdsadmin');
open MY_CURSOR
fetch next from MY_CURSOR into @name
while @@FETCH_STATUS = 0
begin
if(len(@name)>0)
begin
print @name + ' Column Exist'
set @QaQuery = N'select
'''+@name+''' as Name
,sum(case when type = 0 then size else 0 end) as DataFileSizeMB
,sum(case when type = 1 then size else 0 end) as LogFileSizeMB
from ['+@name+'].sys.database_files
group by replace(name, ''_log'', '''')';
insert @Results exec sp_executesql @QaQuery;
end
fetch next from MY_CURSOR into @name
end
close MY_CURSOR
deallocate MY_CURSOR
select * from @Results order by DataFileSizeMB desc
go
Download and install packages and dependencies
Usage:
go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]
Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.
The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.
The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original.
The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code.
The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution.
The -t flag instructs get to also download the packages required to build the tests for the specified packages.
The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.
The -v flag enables verbose progress and debug output.
Get also accepts build flags to control the installation. See 'go help build'.
When checking out a new package, get creates the target directory GOPATH/src/. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'.
When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the default branch of the package.
When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository.
Get never checks out or updates code stored in vendor directories.
For more about specifying packages, see 'go help packages'.
For more about how 'go get' finds source code to download, see 'go help importpath'.
This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help module-get'.
See also: go build, go install, go clean.
For example, showing verbose output,
$ go get -v github.com/capotej/groupcache-db-experiment/...
github.com/capotej/groupcache-db-experiment (download)
github.com/golang/groupcache (download)
github.com/golang/protobuf (download)
github.com/capotej/groupcache-db-experiment/api
github.com/capotej/groupcache-db-experiment/client
github.com/capotej/groupcache-db-experiment/slowdb
github.com/golang/groupcache/consistenthash
github.com/golang/protobuf/proto
github.com/golang/groupcache/lru
github.com/capotej/groupcache-db-experiment/dbserver
github.com/capotej/groupcache-db-experiment/cli
github.com/golang/groupcache/singleflight
github.com/golang/groupcache/groupcachepb
github.com/golang/groupcache
github.com/capotej/groupcache-db-experiment/frontend
$
You also can use itemgetter operator:
from operator import itemgetter
my_tuples = [('c','r'), (2, 3), ('e'), (True, False),('text','sample')]
map(itemgetter(0), my_tuples)
Basically, just use an appropriate onkeypress handler. See http://www.qodo.co.uk/blog/javascript-restrict-keyboard-character-input/ and the example http://www.qodo.co.uk/wp-content/uploads/2008/05/javascript-restrict-keyboard-character-input.html
This makes sure that redirects work for all combinations of intransparent proxies.
This includes the case client <http> proxy <https> webserver.
# behind proxy
RewriteCond %{HTTP:X-FORWARDED-PROTO} ^http$
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
# plain
RewriteCond %{HTTP:X-FORWARDED-PROTO} ^$
RewriteCond %{REQUEST_SCHEME} ^http$ [NC,OR]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
use MAX
in your SELECT
to return on value.. EXAMPLE
INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT MAX(student_id) FROM student), (SELECT MAX(syr_id) FROM school_year))
instead of
INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT (student_id) FROM student), (SELECT (syr_id) FROM school_year))
try it without MAX it will more than one value
Starting with 1.6.4, Arduino IDE can be used to program and upload the NodeMCU board by installing the ESP8266 third-party platform package (refer https://github.com/esp8266/Arduino):
To install additional ESP8266WiFi library:
After above steps, you should compile the sketch normally.
You can do this using generic SQL with group by
:
SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
tbl_Media M
ON M.Content_Id = C.Content_Id
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;
Or with a correlated subquery:
SELECT C.Content_ID, C.Contt_Title,
(SELECT M.Media_Id
FROM tbl_Media M
WHERE M.Content_Id = C.Content_Id
ORDER BY M.MEDIA_ID DESC
LIMIT 1
) as Media_Id
FROM tbl_Contents C
ORDER BY C.Content_DatePublished ASC;
Of course, the syntax for limit 1
varies between databases. Could be top
. Or rownum = 1
. Or fetch first 1 rows
. Or something like that.
ArrayList check = new ArrayList();
for (int i = 0; i < oDS.Tables[0].Rows.Count; i++)
{
int iValue = Convert.ToInt32(oDS.Tables[0].Rows[i][3].ToString());
check.Add(iValue);
}
You need to add below code in your AppDelegate applicationDidBecomeActive
method.
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
If you want to reset your table, you can do
truncate table TableName
truncate needs privileges, and you can't use it if your table has dependents (another tables that have FK of your table,
I would use SWFUpload or Uploadify. They need Flash but do everything you want without troubles.
Any <input type="file">
based workaround that tries to trigger the "open file" dialog by means other than clicking on the actual control could be removed from browsers for security reasons at any time. (I think in the current versions of FF and IE, it is not possible any more to trigger that event programmatically.)
I use in my batch files - c:\progra~2\
instead of C:\Program Files (x86)\
and it works.
In Bash:
if [[ ( $g == 1 && $c == 123 ) || ( $g == 2 && $c == 456 ) ]]
If you are using a windows OS probably this will be your flutter SDK location
C:\src\flutter
If it's not available it's better to choose a path and clone SDK repository
I received this error when the class was annotated with @Ignore and I tried to run a specific test via right clicking on it. Removing the @Ignore fixed the problem.
lodash and typescript
const clearSubTopics = _.filter(obj.subTopics, topic => (!_.isEqual(topic.subTopicId, 2)));
console.log(clearSubTopics);
This is touched in "PowerShell Execution Policies in Standard Images" on Lee Holmes' Blog and "PowerShell’s Security Guiding Principles" on the Windows Power Shell Blog .
Summary
Some machines treat UNC paths as the big bad internet, so PowerShell treats them as remote files. You can either disable this feature on those servers (UncAsIntranet = 0,
) or add the remote machines to your trusted hosts.
If you want to do neither, PowerShell v2 supports an -ExecutionPolicy
parameter that does exactly what your pseudocode wants. PowerShell -ExecutionPolicy Bypass -File (...)
.
Here is another (more complex) way of getting either the filename or extension, first use the rev
command to invert the file path, cut from the first .
and then invert the file path again, like this:
filename=`rev <<< "$1" | cut -d"." -f2- | rev`
fileext=`rev <<< "$1" | cut -d"." -f1 | rev`
Try
$(document).on('change','#multiid',function(){
alert('Change Happened');
});
As your select-box is generated from the code, so you have to use event delegation, where in place of $(document)
you can have closest parent element.
Or
$(document.body).on('change','#multiid',function(){
alert('Change Happened');
});
Update:
Second one works fine, there is another change of selector to make it work.
$('#addbasket').on('change','#multiid',function(){
alert('Change Happened');
});
Ideally we should use $("#addbasket")
as it's the closest parent element [As i have mentioned above].
Oracle Java Communications API Reference - http://www.oracle.com/technetwork/java/index-jsp-141752.html
Official 3.0 Download (Solarix, Linux) - http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-misc-419423.html
Unofficial 2.0 Download (All): http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm
Unofficial 2.0 Download (Windows installer) - http://kishor15389.blogspot.hk/2011/05/how-to-install-java-communications.html
In order to ensure there is no compilation error, place the file on your classpath when compiling (-cp command-line option, or check your IDE documentation).
replace this line of code
import android.support.v4.app.FragmentActivity;
with
import androidx.fragment.app.FragmentActivity;
and you are done.
If Divyesh Rupawala's answer doesn't work (passing the current item as the parameter), then please see the onChanged()
function in this Plunker. It's using this
:
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
mysql> set global sql_slave_skip_counter=1; start slave; show slave status\G
Then got error exists :
Error 'Table './openx/f_scraper_banner_details' is marked as crashed and should be repaired' on query. Default database: 'openx'. Query: 'INSERT INTO f_scraper_banner_details(job_details_id, ad_id, client_id, zone_id, affiliateid, comments, pct_to_report, publisher_currency, sanity_check_enabled, status, error_code, report_date) VALUES (10274859, 321264, 0, 31926, 0, '', -1, 'USD', 1, 'FAILURE', 'INACTIVE_BANNER', '2016-06-28 04:00:00')'
mysql> repair table f_scraper_banner_details;
This worked for me
Try this :)
var mystring = "How do I get a long text string";
mystring = mystring.substring(0,10);
alert(mystring);
You can do this with the following:
int counter = 0;
String sql = "SELECT projectName,Owner " + "FROM Project WHERE Owner= ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setString(1, "");
ResultSet rs = prep.executeQuery();
while (rs.next()) {
counter++;
}
System.out.println(counter);
This will give you the no of rows where the column value is null or blank.
Use a regex to extract the "video id" after watch?v=
Store the video id in a variable, let's call this variable vid
Get the embed code from a random video, remove the video id from the embed code and replace it with the vid
you got.
I don't know how to deal with regex in php, but it shouldn't be too hard
Here's example code in python:
>>> ytlink = 'http://www.youtube.com/watch?v=7-dXUEbBz70'
>>> import re
>>> vid = re.findall( r'v\=([\-\w]+)', ytlink )[0]
>>> vid
'7-dXUEbBz70'
>>> print '''<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/%s&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/%s&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>''' % (vid,vid)
<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>
>>>
The regular expression v\=([\-\w]+)
captures a (sub)string of characters and dashes that comes after v=
Everybody has the right idea, but I like to be a little more explicit and trim the values.
$('#apply-form input').blur(function() {
if(!$.trim(this.value).length) { // zero-length string AFTER a trim
$(this).parents('p').addClass('warning');
}
});
if you dont use .length , then an entry of '0' can get flagged as bad, and an entry of 5 spaces could get marked as ok without the $.trim . Best of Luck.
When create React components from functions
and useState
.
const [drawerState, setDrawerState] = useState(false);
const toggleDrawer = () => {
// attempting to trigger re-render
setDrawerState(!drawerState);
};
This does not work
<Drawer
drawerState={drawerState}
toggleDrawer={toggleDrawer}
/>
This does work (adding key)
<Drawer
drawerState={drawerState}
key={drawerState}
toggleDrawer={toggleDrawer}
/>
You can use iterators:
Mat matrix = ...;
std::vector<float> vec(matrix.begin<float>(), matrix.end<float>());
Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' })
to get the page scrolled with a smooth effect.
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
top: 400,_x000D_
behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
height: 1000px;_x000D_
background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
<button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
You can do something like this:
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
var i = 10;_x000D_
var int = setInterval(function() {_x000D_
window.scrollTo(0, i);_x000D_
i += 10;_x000D_
if (i >= 200) clearInterval(int);_x000D_
}, 20);_x000D_
})
_x000D_
body {_x000D_
background: #3a2613;_x000D_
height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
ES6 recursive approach:
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
let i = h || 0;_x000D_
if (i < 200) {_x000D_
setTimeout(() => {_x000D_
window.scrollTo(0, i);_x000D_
smoothScroll(i + 10);_x000D_
}, 10);_x000D_
}_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
background: #9a6432;_x000D_
height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
Fortes is right, thank you.
When you have a shared hosting it is usual to obtain an 500 server error
.
I have a website with Joomla and I added to the index.php
:
ini_set('display_errors','off');
The error line showed in my website disappeared.
chmod +x gradlew
Just run the above comment. that's all enjoy your coding...
Arrays.sort(yourarray, new Comparator() {
public int compare(Object o1, Object o2) {
String[] elt1 = (String[])o1;
String[] elt2 = (String[])o2;
return elt1[0].compareTo(elt2[0]);
}
});
Try this CSS code for cross-browser compatibility.
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
First Navigate the Path of php.ini
sudo vi /etc/php/7.2/fpm/php.ini
then, next change
upload_max_filesize = 999M
post_max_size = 999M
then ESC-->:wq
Now Lastly Paste this command,
sudo systemctl restart php7.2-fpm.service
you are done.
I had the same issue and tried all the answers mentioned here, none worked.
The simple solution is go to your project folder and delete all the .idea and .iml files and restart the IntelliJ ide. It works. No need to do anything with the settings.
No solution mentioned above was solved my problem. My problem was different.
First check is your port is disabled in firewall.
Go to Control Panel -> Windows Firewall -> Advance Settings -> Inbound Rules
and see any port is blocked.
A sample image is below:
If so then you can unblock the port by following steps:
Step 1:
Here you can see that the port is blocked.
Step 2: Allow the connection -> Apply -> Ok
.
That's solved my blocked problem. Happy coding :) :)
You can use basename()
and $_SERVER['PHP_SELF']
to get current page file name
echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */
In SQL Server 2005+ with Full-Text indexing switched on, I'd do the following:
SELECT *
FROM T
WHERE CONTAINS(C, '"David" OR "Robi" OR "Moses"');
If you wanted your search to bring back results where the result is prefixed with David, Robi or Moses you could do:
SELECT *
FROM T
WHERE CONTAINS(C, '"David*" OR "Robi*" OR "Moses*"');
Well getheight gets the height, and getwidth gets the width. But you're calling those methods too soon. If you're calling them in oncreate or onresume, the view isn't drawn yet. You have to call it after the view has been drawn.
All 3 of them represent the end of a line. But...
\r
(Carriage Return) → moves the cursor to the beginning of the line without advancing to the next line\n
(Line Feed) → moves the cursor down to the next line without returning to the beginning of the line — In a *nix environment \n
moves to the beginning of the line.\r\n
(End Of Line) → a combination of \r
and \n
To avoid the boxing of KeyValuePair.Equals(object)
you can use a ValueTuple
.
if ((getResult.Key, getResult.Value) == default)
Had the same situation. This helped:
Open Package Manager Console
Change directory to Migrations folder:
cd C:\YourSolution\YourProjectWithMigrations
Enter in PM:
dotnet ef migrations add YourMigrationName
As mentioned in other answers you can use:
>> tic; x=5*ones(10,1); toc
Elapsed time is 0.000415 seconds.
An even faster method is:
>> tic; x=5; x=x(ones(10,1)); toc
Elapsed time is 0.000257 seconds.
wmic bios get serialnumber
if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)
I had to do exactly that.:):)
AndroidRate is a library to help you promote your android app by prompting users to rate the app after using it for a few days.
Module Gradle:
dependencies {
implementation 'com.vorlonsoft:androidrate:1.0.8'
}
MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppRate.with(this)
.setStoreType(StoreType.GOOGLEPLAY) //default is GOOGLEPLAY (Google Play), other options are
// AMAZON (Amazon Appstore) and
// SAMSUNG (Samsung Galaxy Apps)
.setInstallDays((byte) 0) // default 10, 0 means install day
.setLaunchTimes((byte) 3) // default 10
.setRemindInterval((byte) 2) // default 1
.setRemindLaunchTimes((byte) 2) // default 1 (each launch)
.setShowLaterButton(true) // default true
.setDebug(false) // default false
//Java 8+: .setOnClickButtonListener(which -> Log.d(MainActivity.class.getName(), Byte.toString(which)))
.setOnClickButtonListener(new OnClickButtonListener() { // callback listener.
@Override
public void onClickButton(byte which) {
Log.d(MainActivity.class.getName(), Byte.toString(which));
}
})
.monitor();
if (AppRate.with(this).getStoreType() == StoreType.GOOGLEPLAY) {
//Check that Google Play is available
if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) != ConnectionResult.SERVICE_MISSING) {
// Show a dialog if meets conditions
AppRate.showRateDialogIfMeetsConditions(this);
}
} else {
// Show a dialog if meets conditions
AppRate.showRateDialogIfMeetsConditions(this);
}
}
The default conditions to show rate dialog is as below:
AppRate#setInstallDays(byte)
.AppRate#setLaunchTimes(byte)
.AppRate#setRemindInterval(byte)
.AppRate#setRemindLaunchTimes(byte)
.setShowLaterButton(boolean)
.DialogInterface.OnClickListener#onClick
will be passed in the argument of onClickButton
.AppRate#setDebug(boolean)
will ensure that the rating request is shown each time the app is launched. This feature is only for development!.You can add additional optional requirements for showing dialog. Each requirement can be added/referenced as a unique string. You can set a minimum count for each such event (for e.g. "action_performed" 3 times, "button_clicked" 5 times, etc.)
AppRate.with(this).setMinimumEventCount(String, short);
AppRate.with(this).incrementEventCount(String);
AppRate.with(this).setEventCountValue(String, short);
When you want to show the dialog again, call AppRate#clearAgreeShowDialog()
.
AppRate.with(this).clearAgreeShowDialog();
call AppRate#showRateDialog(Activity)
.
AppRate.with(this).showRateDialog(this);
call AppRate#setView(View)
.
LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_dialog, (ViewGroup)findViewById(R.id.layout_root));
AppRate.with(this).setView(view).monitor();
You can use a specific theme to inflate the dialog.
AppRate.with(this).setThemeResId(int);
If you want to use your own dialog labels, override string xml resources on your application.
<resources>
<string name="rate_dialog_title">Rate this app</string>
<string name="rate_dialog_message">If you enjoy playing this app, would you mind taking a moment to rate it? It won\'t take more than a minute. Thanks for your support!</string>
<string name="rate_dialog_ok">Rate It Now</string>
<string name="rate_dialog_cancel">Remind Me Later</string>
<string name="rate_dialog_no">No, Thanks</string>
</resources>
if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) != ConnectionResult.SERVICE_MISSING) {
}
int x;
ifile >> x
while (!iFile.eof())
{
cerr << x << endl;
iFile >> x;
}
Are you looking for a particular extension? In your phpinfo();
, just hit Ctrl+F in your web browser, type in the first 3-4 letters of the extension you're looking for, and it should show you whether or not its loaded.
Usually in phpinfo()
it doesn't show you all the loaded extensions in one location, it has got a separate section for each loaded extension where it shows all of its variables, file paths, etc, so if there is no section for your extension name it probably means it isn't loaded.
Alternatively you can open your php.ini file and use the Ctrl+F method to find your extension, and see if its been commented out (usually by a semicolon near the start of the line).
A workaround to consider in a pinch:
The data in the database will have the quotes once the import is done... you can update the data later on to remove the quotes, or use the "replace" function in your read query, such as "replace([dbo].[MyTable].[MyColumn], '''', '')"
I'm just returning to this question after taking sth's answer and making a small but very useful modification. This function prints all keys in the JSON tree as well as the size of leaf nodes in that tree.
def print_JSON_tree(d, indent=0):
for key, value in d.iteritems():
print ' ' * indent + unicode(key),
if isinstance(value, dict):
print; print_JSON_tree(value, indent+1)
else:
print ":", str(type(d[key])).split("'")[1], "-", str(len(unicode(d[key])))
It's really nice when you have large JSON objects and want to figure out where the meat is. Example:
>>> print_JSON_tree(JSON_object)
key1
value1 : int - 5
value2 : str - 16
key2
value1 : str - 34
value2 : list - 5623456
This would tell you that most of the data you care about is probably inside JSON_object['key1']['key2']['value2']
because the length of that value formatted as a string is very large.
I had the same problem. I tried everything listed on this page. When I re-installed Composer it worked like before. I had a PHP version mismatch that was corrected with a new install establishing the dependencies with the PHP path installed in my system environment variables.
I DO NOT RECOMMEND the composer config -g -- disable-tls true
approach.
By the way the way to reverse this is composer config -g -- disable-tls false
.
I am answering bit late to this question, but someone, in future, might find this useful. The below approach, besides lots of other approaches, works best, and I personally think would better suit a web application.
@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
... other configurations
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.propertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
builder.serializationInclusion(Include.NON_EMPTY);
builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
}
}
Check your Web.Config and find namespace = . you can remove or if you need it you must create new
It works as well if we set color for each elements for example: I added some Margin to left now.
<article class="event-item">
<p>Black text here</p>
</article>
.event-item{
list-style-type: disc;
display: list-item;
color: #ff6f9a;
margin-left: 25px;
}
.event-item p {
margin: 0;
color: initial;
}
The error is self explanatory:
A good check I often use is to use telnet, eg on a windows command prompt run:
telnet 127.0.0.1 1433
If you get a blank screen it indicates network connection established successfully, and it's not a network problem. If you get 'Could not open connection to the host' then this is network problem
While the Java language does not directly support operator overloading, you can use the Manifold compiler plugin in any Java project to enable it. It supports Java 8 - 13 (the current Java version) and is fully supported in IntelliJ IDEA.
I would do something like this:
boolean foundQuote = false;
if(charAtIndex(currentStringIndex) == '"')
{
foundQuote = true;
}
if(foundQuote == true)
{
//do nothing
}
else
{
string[] split = currentString.split(',');
}
Can you give us a better description and an example of what you are doing? Because all i have to do is put the line in there for the device and then save the file. Now just reconnect the device and it works.
I usually use something similar to this line:
;
;some name for the phone (this seems to be arbitrary)
%CompositeAdbInterface% = USB_Install, THE_HARDWARE_ID
What i do, is:
android_winusb.inf
. Your_Android_SDK_Directory/extras/google/usb_driver/
That seems to always work for me, is that what you are doing? Or does this even help?
And for now, here is https://github.com/google/go-cmp which
is intended to be a more powerful and safer alternative to
reflect.DeepEqual
for comparing whether two values are semantically equal.
package main
import (
"fmt"
"github.com/google/go-cmp/cmp"
)
func main() {
a := []byte{1, 2, 3}
b := []byte{1, 2, 3}
fmt.Println(cmp.Equal(a, b)) // true
}
Not a UUID, but this works for me:
UUID.randomUUID().toString().replace("-","").substring(0,8)
.parent {
display: table;
table-layout: fixed;
}
.child {
display:table-cell;
vertical-align:middle;
text-align:center;
}
table-layout: fixed
prevents breaking the functionality of the col-* classes.
This question is old, but I wanted to add my two-cents. I read the question as " I want to run a query to my [my]SQL database and store the returned data as Pandas data structure [DataFrame]."
From the code it looks like you mean mysql database and assume you mean pandas DataFrame.
import MySQLdb as mdb
import pandas.io.sql as sql
from pandas import *
conn = mdb.connect('<server>','<user>','<pass>','<db>');
df = sql.read_frame('<query>', conn)
For example,
conn = mdb.connect('localhost','myname','mypass','testdb');
df = sql.read_frame('select * from testTable', conn)
This will import all rows of testTable into a DataFrame.
Because the inequality operator in VBA is <>
If strTest <> "" Then
.....
the operator !=
is used in C#, C++.
Since for some reason white isn't available for selection, I have found that mat-palette($mat-grey, 50)
was close enough to white, for my needs at least.
Here's a guided approach.
Your authentication service issues a JWT token that is signed using a secret that is also available in your API service. The reason they need to be there too is that you will need to verify the tokens received to make sure you created them. The nice thing about JWTs is that their payload can hold claims as to what the user is authorised to access should different users have different access control levels.
That architecture renders authentication stateless: No need to store any tokens in a database unless you would like to handle token blacklisting (think banning users). Being stateless is crucial if you ever need to scale. That also frees up your API service from having to call the authentication server at all as the information they need for both authentication and authorisation are in the issued token.
Flow (no refresh tokens):
There are a couple of issues here. Namely, that auth token in the wrong hands provides unlimited access to a malicious user to pretend they are the affected user and call your APIs indefinitely. To handle that, tokens have an expiry date and clients are forced to request new tokens whenever expiry happens. That expiry is part of the token's payload. But if tokens are short-lived, do we require users to authenticate with their usernames and password every time? No. We do not want to ask a user for their password every 30min to an hour, and we do not want to persist that password anywhere in the client. To get around that issue, we introduce the concept of refresh tokens. They are longer lived tokens that serve one purpose: act as a user's password, authenticate them to get a new token. Downside is that with this architecture your authentication server needs to persist these refresh token in a database.
New flow (with refresh tokens):
OPTIONAL (banning users)
How do we ban users? Using that model there is no easy way to do so. Enhancement: Every persisted refresh token includes a blacklisted field and only issue new tokens if the refresh token isn't black listed.
Things to consider:
Here is the beginning of my response to your update:
Why does the content height of my UIWebView not change with rotation?.
Could it be that because your auto resize doesn't have the autoresizingMask for all directions?
Another suggestion before I come back for this, could you use a toolbar for your needs. It's a little simpler, will always be on the bottom, auto-rotates/positions. You can hide/show it at will etc. Kind of like this: http://cdn.artoftheiphone.com/wp-content/uploads/2009/01/yellow-pages-iphone-app-2.jpg
You may have looked at that option, but just throwing it out there.
Another idea, could you possibly detect what orientation you are rotating from, and just place the button programmatically to adjust for the tab bar. (This is possible with code)
public void dateDifferenceExample() {
// Set the date for both of the calendar instance
GregorianCalendar calDate = new GregorianCalendar(2012, 10, 02,5,23,43);
GregorianCalendar cal2 = new GregorianCalendar(2015, 04, 02);
// Get the represented date in milliseconds
long millis1 = calDate.getTimeInMillis();
long millis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = millis2 - millis1;
// Calculate difference in seconds
long diffSeconds = diff / 1000;
// Calculate difference in minutes
long diffMinutes = diff / (60 * 1000);
// Calculate difference in hours
long diffHours = diff / (60 * 60 * 1000);
// Calculate difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);
Toast.makeText(getContext(), ""+diffSeconds, Toast.LENGTH_SHORT).show();
}
Here's an example (source):
SET @randomId = Cast(((@maxValue + 1) - @minValue) * Rand() + @minValue AS tinyint);
It has 2 possible solutions:
1) You can set it in the view by javascript... (not recomended)
<input class="form-control"
type="text"
id="tbFormControll"
th:field="*{clientName}"/>
<script type="text/javascript">
document.getElementById("tbFormControll").value = "default";
</script>
2) Or the better solution is to set the value in the model, that you attach to the view in GET operation by a controller. You can also change the value in the controller, just make a Java object from $client.name and call setClientName.
public class FormControllModel {
...
private String clientName = "default";
public String getClientName () {
return clientName;
}
public void setClientName (String value) {
clientName = value;
}
...
}
I hope it helps.
use "Content-type: application/x-www-form-urlencoded" instead of "application/json"