As David Olsson has said, you can use HTML in your string resources:
<resource>
<string name="my_string">A string with <i>actual</i> <b>formatting</b>!</string>
</resources>
Then if you use getText(R.string.my_string)
rather than getString(R.string.my_string)
you get back a CharSequence
rather than a String
that contains the formatting embedded.
$(document).ready(function () {
$('input[type="text"]').blur(function () {
if (!$(this).val()) {
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
});
});
<style>
.error {
border: 1px solid #ff0000;
}
</style>
Swift 3
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var edtEmail: UITextField!
@IBOutlet var bottomTextfieldConstrain: NSLayoutConstraint! // <- this guy is the constrain that connect the bottom of textField to lower object or bottom of page!
@IBAction func edtEmailEditingDidBegin(_ sender: Any) {
self.bottomTextfieldConstrain.constant = 200
let point = CGPoint(x: 0, y: 200)
scrollView.contentOffset = point
}
@IBAction func edtEmailEditingDidEnd(_ sender: Any) {
self.bottomTextfieldConstrain.constant = 50
}
In my case I had a file built by external dependency (xsd2code) and somehow its designer.cs files were not processed by VS correctly. Creating a new file in Visual Studio and pasting the code in it did the trick for me.
I know this is an old thread, but I wanted to test if a machine was up on my system and unless I have misunderstood, none of the above works if my router reports that an address is unreachable. I am using a batch file rather than a script because I wanted to "KISS" on pretty much any WIN machine. So the approach I used was to do more than one ping and test for "Lost = 0" as follows
ping -n 2 %pingAddr% | find /I "Lost = 0"
if %errorlevel% == 0 goto OK
I haven't tested this rigorously but so far it does the job for me
Thanks to Rob, Updated Swift 4.2 syntax
let controller:WalletView = self.storyboard!.instantiateViewController(withIdentifier: "MyView") as! WalletView
controller.view.frame = self.view.bounds
self.view.addSubview(controller.view)
self.addChild(controller)
controller.didMove(toParent: self)
G'day, I too can say that I tried everything mentioned in these posts and a few more from elsewhere. The #1 problem for me was that the new Intent always had a null bundle. My issue was in focusing too much on the details of "have I included .this or .that". My solution was in taking a step back from the detail and looking at the overall structure of the notification. When I did that I managed to place the key parts of the code in the correct sequence. So, if you're having similar issues check for:
1. Intent notificationIntent = new Intent(MainActivity.this, NotificationActivity.class);
2a. Bundle bundle = new Bundle();
//I like specifying the data type much better. eg bundle.putInt
2b. notificationIntent.putExtras(bundle);
3. PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, WIZARD_NOTIFICATION_ID, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
4. NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
5. NotificationCompat.Builder nBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notify)
.setContentTitle(title)
.setContentText(content)
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setAutoCancel(false)//false is standard. true == automatically removes the notification when the user taps it.
.setColor(getResources().getColor(R.color.colorPrimary))
.setCategory(Notification.CATEGORY_REMINDER)
.setPriority(Notification.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notificationManager.notify(WIZARD_NOTIFICATION_ID, nBuilder.build());
With this sequence I get a valid bundle.
add this line in your css file:
.classname ul li {
float: left;
}
export PATH=/usr/pgsql-9.2/bin:$PATH
The program executable psql
is in the directory /usr/pgsql-9.2/bin
, and that directory is not included in the path by default, so we have to tell our shell (terminal) program where to find psql
. When most packages are installed, they are added to an existing path, such as /usr/local/bin
, but not this program.
So we have to add the program's path to the shell PATH variable if we do not want to have to type the complete path to the program every time we execute it.
This line should typically be added to theshell startup script, which for the bash shell will be in the file ~/.bashrc
.
Here is the simple version
#one
a = [[0]*10]*10
#two
row, col = 10, 10
a = [[0]*row]*col
First add the new files:
svn add fileName
Then commit all new and modified files
svn ci <files_separated_by_space> -m "Commit message|ReviewID:XXXX"
If non source files are to be committed then
svn ci <files> -m "Commit msg|ReviewID:NON-SOURCE"
Use Modernizr for detection of feature capabilities. In general jQuery offers to detect browser features: http://api.jquery.com/jQuery.support/. However, hashchange is not on the list.
The wiki of Modernizr offers a list of libraries to add HTML5 capabilities to old browsers. The list for hashchange includes a pointer to the project HTML5 History API, which seems to offer the functionality you would need if you wanted to emulate the behavior in old browsers.
That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:
public ActionResult SomeAction()
{
...
return RedirectToAction("SomeAction", "SomeController");
}
Now since I see that in your example you are attempting to redirect to the LogOn
action, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize]
attribute:
[Authorize]
public ActionResult SomeProtectedAction()
{
...
}
Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl
).
To do POST you'll need to have a form.
<form action="employee.action" method="post">
<input type="submit" value="Employee1" />
</form>
There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.
Some tricks: Make a link use POST instead of GET and How do you post data with a link
Edit: to load response on a frame you can target your form to your frame:
<form action="employee.action" method="post" target="myFrame">
You're missing quotes around your string:
...
var htmlString="<?php echo $htmlString; ?>";
...
You can use 'category_name' in parameters. http://codex.wordpress.org/Template_Tags/get_posts
Note: The category_name parameter needs to be a string, in this case, the category name.
There are several steps when using OpenSSL. You must have an SSL certificate made which can contain the certificate with the private key be sure to specify the exact location of the certificate (this example has it in the root). There are a lot of good tutorials out there.
Some includes:
#include <openssl/applink.c>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
You will need to initialize OpenSSL:
void InitializeSSL()
{
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
}
void DestroySSL()
{
ERR_free_strings();
EVP_cleanup();
}
void ShutdownSSL()
{
SSL_shutdown(cSSL);
SSL_free(cSSL);
}
Now for the bulk of the functionality. You may want to add a while loop on connections.
int sockfd, newsockfd;
SSL_CTX *sslctx;
SSL *cSSL;
InitializeSSL();
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd< 0)
{
//Log and Error
return;
}
struct sockaddr_in saiServerAddress;
bzero((char *) &saiServerAddress, sizeof(saiServerAddress));
saiServerAddress.sin_family = AF_INET;
saiServerAddress.sin_addr.s_addr = serv_addr;
saiServerAddress.sin_port = htons(aPortNumber);
bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
listen(sockfd,5);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
sslctx = SSL_CTX_new( SSLv23_server_method());
SSL_CTX_set_options(sslctx, SSL_OP_SINGLE_DH_USE);
int use_cert = SSL_CTX_use_certificate_file(sslctx, "/serverCertificate.pem" , SSL_FILETYPE_PEM);
int use_prv = SSL_CTX_use_PrivateKey_file(sslctx, "/serverCertificate.pem", SSL_FILETYPE_PEM);
cSSL = SSL_new(sslctx);
SSL_set_fd(cSSL, newsockfd );
//Here is the SSL Accept portion. Now all reads and writes must use SSL
ssl_err = SSL_accept(cSSL);
if(ssl_err <= 0)
{
//Error occurred, log and close down ssl
ShutdownSSL();
}
You are then able read or write using:
SSL_read(cSSL, (char *)charBuffer, nBytesToRead);
SSL_write(cSSL, "Hi :3\n", 6);
Update
The SSL_CTX_new
should be called with the TLS method that best fits your needs in order to support the newer versions of security, instead of SSLv23_server_method()
. See:
OpenSSL SSL_CTX_new description
TLS_method(), TLS_server_method(), TLS_client_method(). These are the general-purpose version-flexible SSL/TLS methods. The actual protocol version used will be negotiated to the highest version mutually supported by the client and the server. The supported protocols are SSLv3, TLSv1, TLSv1.1, TLSv1.2 and TLSv1.3.
This is is another working solution to the problem:
public void test (){
Map<String, String> keyValueStore = new HasMap<>();
Stack<String> keyPath = new Stack();
JSONObject json = new JSONObject("thisYourJsonObject");
keyValueStore = getAllXpathAndValueFromJsonObject(json, keyValueStore, keyPath);
for(Map.Entry<String, String> map : keyValueStore.entrySet()) {
System.out.println(map.getKey() + ":" + map.getValue());
}
}
public Map<String, String> getAllXpathAndValueFromJsonObject(JSONObject json, Map<String, String> keyValueStore, Stack<String> keyPath) {
Set<String> jsonKeys = json.keySet();
for (Object keyO : jsonKeys) {
String key = (String) keyO;
keyPath.push(key);
Object object = json.get(key);
if (object instanceof JSONObject) {
getAllXpathAndValueFromJsonObject((JSONObject) object, keyValueStore, keyPath);
}
if (object instanceof JSONArray) {
doJsonArray((JSONArray) object, keyPath, keyValueStore, json, key);
}
if (object instanceof String || object instanceof Boolean || object.equals(null)) {
String keyStr = "";
for (String keySub : keyPath) {
keyStr += keySub + ".";
}
keyStr = keyStr.substring(0, keyStr.length() - 1);
keyPath.pop();
keyValueStore.put(keyStr, json.get(key).toString());
}
}
if (keyPath.size() > 0) {
keyPath.pop();
}
return keyValueStore;
}
public void doJsonArray(JSONArray object, Stack<String> keyPath, Map<String, String> keyValueStore, JSONObject json,
String key) {
JSONArray arr = (JSONArray) object;
for (int i = 0; i < arr.length(); i++) {
keyPath.push(Integer.toString(i));
Object obj = arr.get(i);
if (obj instanceof JSONObject) {
getAllXpathAndValueFromJsonObject((JSONObject) obj, keyValueStore, keyPath);
}
if (obj instanceof JSONArray) {
doJsonArray((JSONArray) obj, keyPath, keyValueStore, json, key);
}
if (obj instanceof String || obj instanceof Boolean || obj.equals(null)) {
String keyStr = "";
for (String keySub : keyPath) {
keyStr += keySub + ".";
}
keyStr = keyStr.substring(0, keyStr.length() - 1);
keyPath.pop();
keyValueStore.put(keyStr , json.get(key).toString());
}
}
if (keyPath.size() > 0) {
keyPath.pop();
}
}
You can set display attribute as none to hide a label.
<label id="excel-data-div" style="display: none;"></label>
If you already have a test class, but missing the JUnit library dependency, please refer to Configuring Libraries for Unit Testing documentation section. Pressing Alt+Enter on the red code should give you an intention action to add the missing jar.
However, IDEA offers much more. If you don't have a test class yet and want to create one for any of the source classes, see instructions below.
You can use the Create Test intention action by pressing Alt+Enter while standing on the name of your class inside the editor or by using Ctrl+Shift+T keyboard shortcut.
A dialog appears where you select what testing framework to use and press Fix button for the first time to add the required library jars to the module dependencies. You can also select methods to create the test stubs for.
You can find more details in the Testing help section of the on-line documentation.
I had this problem recently, my project didn't include local.properties
file.
Check local.properties
file if it includes sdk.dir
with correct path to sdk
You can use FLOOR
:
select x, ABS(x) - FLOOR(ABS(x))
from (
select 2.938 as x
) a
Output:
x
-------- ----------
2.938 0.938
Or you can use SUBSTRING
:
select x, SUBSTRING(cast(x as varchar(max)), charindex(cast(x as varchar(max)), '.') + 3, len(cast(x as varchar(max))))
from (
select 2.938 as x
) a
It was already mentioned, but thought I could add to using touch
If you touch
all the source files to be compiled, the touch
command changes the timestamps of a file to the system time the touch
command was executed.
The source file timstamp is what make
uses to "know" a file has changed, and needs to be re-compiled
For example: If the project was a c++ project, then do touch *.cpp
, then run make
again, and make should recompile the entire project.
Isn't it better with a group by? Something like:
SELECT COUNT(*) FROM t1 GROUP BY keywork;
Just in case if someone is wondering to save the CSV file to a specific path for email attachments. Then it can be done as follows
I know I have added a lot of comments just for newbies :)
I have added an example so that you can summarize well.
$activeUsers = /** Query to get the active users */
/** Following is the Variable to store the Users data as
CSV string with newline character delimiter,
its good idea of check the delimiter based on operating system */
$userCSVData = "Name,Email,CreatedAt\n";
/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user ) {
$userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
}
/** Here you can use with H:i:s too. But I really dont care of my old file */
$todayDate = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName = 'Active Users '.$todayDate.'.csv';
$filePath = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file
/** Just in case if I run the script multiple time
I want to remove the old file and add new file.
And before deleting the file from the location I am making sure it exists */
if(file_exists($filePath)){
unlink($filePath);
}
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */
fclose($fp);
/** Now you can send email with attachments from the $filePath */
NOTE: The following is a very bad idea to increase the memory_limit and time limit, but I have only added to make sure if anyone faces the problem of connection time out or any other. Make sure to find out some alternative before sticking to it.
You have to add the following at the start of the above script.
ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');
You can get table/view details through below query.
For table :sp_help table_name For View :sp_help view_name
You can create your mask array in one step like this
mask_data = input_mask_data < 3
This creates a boolean array which can then be used as a pixel mask. Note that we haven't changed the input array (as in your code) but have created a new array to hold the mask data - I would recommend doing it this way.
>>> input_mask_data = np.random.randint(0, 5, (3, 4))
>>> input_mask_data
array([[1, 3, 4, 0],
[4, 1, 2, 2],
[1, 2, 3, 0]])
>>> mask_data = input_mask_data < 3
>>> mask_data
array([[ True, False, False, True],
[False, True, True, True],
[ True, True, False, True]], dtype=bool)
>>>
This is ES6 (with let declaration).
function checkExistingDate(year, month, day){ // year, month and day should be numbers
// months are intended from 1 to 12
let months31 = [1,3,5,7,8,10,12]; // months with 31 days
let months30 = [4,6,9,11]; // months with 30 days
let months28 = [2]; // the only month with 28 days (29 if year isLeap)
let isLeap = ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
let valid = (months31.indexOf(month)!==-1 && day <= 31) || (months30.indexOf(month)!==-1 && day <= 30) || (months28.indexOf(month)!==-1 && day <= 28) || (months28.indexOf(month)!==-1 && day <= 29 && isLeap);
return valid; // it returns true or false
}
In this case I've intended months from 1 to 12. If you prefer or use the 0-11 based model, you can just change the arrays with:
let months31 = [0,2,4,6,7,9,11];
let months30 = [3,5,8,10];
let months28 = [1];
If your date is in form dd/mm/yyyy than you can take off day, month and year function parameters, and do this to retrieve them:
let arrayWithDayMonthYear = myDateInString.split('/');
let year = parseInt(arrayWithDayMonthYear[2]);
let month = parseInt(arrayWithDayMonthYear[1]);
let day = parseInt(arrayWithDayMonthYear[0]);
From my understanding of the code provided above, it loads the file and does map operation and saves it back. There is no operation that requires shuffle. Also, there is no operation that requires data to be brought to the driver hence tuning anything related to shuffle or driver may have no impact. The driver does have issues when there are too many tasks but this was only till spark 2.0.2 version. There can be two things which are going wrong.
Ahah! Checkout the previous commit, then checkout the master.
git checkout HEAD^
git checkout -f master
When you create a stored routine that has a BEGIN...END
block, statements within the block are terminated by semicolon (;)
. But the CREATE PROCEDURE
statement also needs a terminator. So it becomes ambiguous whether the semicolon within the body of the routine terminates CREATE PROCEDURE
, or terminates one of the statements within the body of the procedure.
The way to resolve the ambiguity is to declare a distinct string (which must not occur within the body of the procedure) that the MySQL client recognizes as the true terminator for the CREATE PROCEDURE
statement.
Looking at Biju's answer I found a working solution.
I created an extra context-file test-context.xml
:
<context:property-placeholder location="classpath:config/spring-test.properties"/>
Containing the profile:
spring.profiles.active=localtest
And loading the test with:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration(locations = {
"classpath:config/test-context.xml" })
public class TestContext {
@Test
public void testContext(){
}
}
This saves some work when creating multiple test-cases.
You can use the function TIME(h,m,s) of google spreadsheet. If you want to add times to each other (or other arithmetic operations), you can specify either a cell, or a call to TIME, for each input of the formula.
For example:
Finally, the Chrome team will release a fix for this issue with Chrome 37 which will be released to public in July 2014. See example comparison of current stable Chrome 35 and latest Chrome 37 (early development preview) here:
1.) There is NO proper solution when loading fonts via @import
, <link href=
or Google's webfont.js
. The problem is that Chrome simply requests .woff files from Google's API which render horribly. Surprisingly all other font file types render beautifully. However, there are some CSS tricks that will "smoothen" the rendered font a little bit, you'll find the workaround(s) deeper in this answer.
2.) There IS a real solution for this when self-hosting the fonts, first posted by Jaime Fernandez in another answer on this Stackoverflow page, which fixes this issue by loading web fonts in a special order. I would feel bad to simply copy his excellent answer, so please have a look there. There is also an (unproven) solution that recommends using only TTF/OTF fonts as they are now supported by nearly all browsers.
3.) The Google Chrome developer team works on that issue. As there have been several huge changes in the rendering engine there's obviously something in progress.
I've written a large blog post on that issue, feel free to have a look: How to fix the ugly font rendering in Google Chrome
See how the example from the initial question look today, in Chrome 29:
Left: Firefox 23, right: Chrome 29
Top: Firefox 23, bottom: Chrome 29
Fixing the above screenshot with -webkit-text-stroke:
First row is default, second has:
-webkit-text-stroke: 0.3px;
Third row has:
-webkit-text-stroke: 0.6px;
So, the way to fix those fonts is simply giving them
-webkit-text-stroke: 0.Xpx;
or the RGBa syntax (by nezroy, found in the comments! Thanks!)
-webkit-text-stroke: 1px rgba(0,0,0,0.1)
There's also an outdated possibility: Give the text a simple (fake) shadow:
text-shadow: #fff 0px 1px 1px;
RGBa solution (found in Jasper Espejo's blog):
text-shadow: 0 0 1px rgba(51,51,51,0.2);
If you want to be updated on this issue, have a look on the according blog post: How to fix the ugly font rendering in Google Chrome. I'll post news if there're news on this.
This is a big bug in Google Chrome and the Google Chrome Team does know about this, see the official bug report here. Currently, in May 2013, even 11 months after the bug was reported, it's not solved. It's a strange thing that the only browser that messes up Google Webfonts is Google's own browser Chrome (!). But there's a simple workaround that will fix the problem, please see below for the solution.
STATEMENT FROM GOOGLE CHROME DEVELOPMENT TEAM, MAY 2013
Official statement in the bug report comments:
Our Windows font rendering is actively being worked on. ... We hope to have something within a milestone or two that developers can start playing with. How fast it goes to stable is, as always, all about how fast we can root out and burn down any regressions.
I might be off here, but it seems that the answer is quite obvious: Look at reference paths in the project properties. In our setup I added our common repository folder, to the ref path GUI window, like so
That way I can copy my dlls (ready for publish) to this folder and every developer now gets the updated DLL every time it builds from this folder.
If the dll is found in the Solution, the builder should prioritize the local version over the published team version.
Because of the condition in while
, the loop might never break:
while (entry != null) {
// If entry never becomes null here, loop will never break.
}
Instead of the null
check there, you can try this:
ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
// Rest of your code
}
Hope this work
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print (word)
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print(word)
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
print ("Let's practice everything.")
print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explantion
\n\t\twhere there is none.
"""
print ("--------------")
print (poem)
print ("--------------")
five = 10 - 2 + 3 - 5
print ("This should be five: %s" % five)
def secret_formula(start_point):
jelly_beans = start_point * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
jelly_beans, jars, crates = secret_formula(start_point)
print ("With a starting point of: %d" % start_point)
print ("We'd have %d jeans, %d jars, and %d crates." % (jelly_beans, jars, crates))
start_point = start_point / 10
print ("We can also do that this way:")
print ("We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point))
sentence = "All god\tthings come to those who weight."
words = break_words(sentence)
sorted_words = sort_words(words)
print_first_word(words)
print_last_word(words)
print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = sort_sentence(sentence)
print (sorted_words)
print_first_and_last(sentence)
print_first_and_last_sorted(sentence)
For me THIS works -
Finding Merging Errors in AndroidManifest.xml
Click on Merged Manifest in AndroidManifest.xml
You can view manifest merging error in right column. It may help to solve this problem.
I think you could do it by creating parameters in an object maybe?
var myObject = {}; for(var i=0;i<myArray.length;i++) { myObject[ myArray[i] ]; }
If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.
Given decimal d=12.345; the expressions d.ToString("C") or String.Format("{0:C}", d) yield $12.35 - note that the current culture's currency settings including the symbol are used.
Note that "C" uses number of digits from current culture. You can always override default to force necessary precision with C{Precision specifier}
like String.Format("{0:C2}", 5.123d)
.
In addition to this, due to some recent website hacks we had to secure our sites more. In doing so, we discovered that file_get_contents failed to work, where curl still would work.
Not 100%, but I believe that this php.ini setting may have been blocking the file_get_contents request.
; Disable allow_url_fopen for security reasons
allow_url_fopen = 0
Either way, our code now works with curl.
I shamelessly converted Apache Common's toBoolean
to JavaScript:
JSFiddle: https://jsfiddle.net/m2efvxLm/1/
Code:
function toBoolean(str) {_x000D_
if (str == "true") {_x000D_
return true;_x000D_
}_x000D_
if (!str) {_x000D_
return false;_x000D_
}_x000D_
switch (str.length) {_x000D_
case 1: {_x000D_
var ch0 = str.charAt(0);_x000D_
if (ch0 == 'y' || ch0 == 'Y' ||_x000D_
ch0 == 't' || ch0 == 'T' ||_x000D_
ch0 == '1') {_x000D_
return true;_x000D_
}_x000D_
if (ch0 == 'n' || ch0 == 'N' ||_x000D_
ch0 == 'f' || ch0 == 'F' ||_x000D_
ch0 == '0') {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 2: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
if ((ch0 == 'o' || ch0 == 'O') &&_x000D_
(ch1 == 'n' || ch1 == 'N') ) {_x000D_
return true;_x000D_
}_x000D_
if ((ch0 == 'n' || ch0 == 'N') &&_x000D_
(ch1 == 'o' || ch1 == 'O') ) {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 3: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
var ch2 = str.charAt(2);_x000D_
if ((ch0 == 'y' || ch0 == 'Y') &&_x000D_
(ch1 == 'e' || ch1 == 'E') &&_x000D_
(ch2 == 's' || ch2 == 'S') ) {_x000D_
return true;_x000D_
}_x000D_
if ((ch0 == 'o' || ch0 == 'O') &&_x000D_
(ch1 == 'f' || ch1 == 'F') &&_x000D_
(ch2 == 'f' || ch2 == 'F') ) {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 4: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
var ch2 = str.charAt(2);_x000D_
var ch3 = str.charAt(3);_x000D_
if ((ch0 == 't' || ch0 == 'T') &&_x000D_
(ch1 == 'r' || ch1 == 'R') &&_x000D_
(ch2 == 'u' || ch2 == 'U') &&_x000D_
(ch3 == 'e' || ch3 == 'E') ) {_x000D_
return true;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 5: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
var ch2 = str.charAt(2);_x000D_
var ch3 = str.charAt(3);_x000D_
var ch4 = str.charAt(4);_x000D_
if ((ch0 == 'f' || ch0 == 'F') &&_x000D_
(ch1 == 'a' || ch1 == 'A') &&_x000D_
(ch2 == 'l' || ch2 == 'L') &&_x000D_
(ch3 == 's' || ch3 == 'S') &&_x000D_
(ch4 == 'e' || ch4 == 'E') ) {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
default:_x000D_
break;_x000D_
}_x000D_
_x000D_
return false;_x000D_
}_x000D_
console.log(toBoolean("yEs")); // true_x000D_
console.log(toBoolean("yES")); // true_x000D_
console.log(toBoolean("no")); // false_x000D_
console.log(toBoolean("NO")); // false_x000D_
console.log(toBoolean("on")); // true_x000D_
console.log(toBoolean("oFf")); // false
_x000D_
Inspect this element, and view the console output.
_x000D_
You can add color in the style rule of your input: color:#ccc;
This worked for me:
gunicorn app:app -b :8080 --timeout 120 --workers=3 --threads=3 --worker-connections=1000
If you have eventlet
add:
--worker-class=eventlet
If you have gevent
add:
--worker-class=gevent
Server.Transfer doesn't change the URL in the client browser, so effectively the browser does not know you changed to another server-side handler. Response.Redirect tells the browser to move to a different page, so the url in the titlebar changes.
Server.Transfer is slightly faster since it avoids one roundtrip to the server, but the non-change of url may be either good or bad for you, depending on what you're trying to do.
It happens when you have a file with the same name as Makefile target name in the directory where the Makefile is present.
It does not work in jQuery 1.9. Made this plugin based on user2444818's answer.
jQuery.fn.mouseIsOver = function () {
return $(this).parent().find($(this).selector + ":hover").length > 0;
};
The authenticity token is used to prevent Cross-Site Request Forgery attacks (CSRF). To understand the authenticity token, you must first understand CSRF attacks.
Suppose that you are the author of bank.com
. You have a form on your site that is used to transfer money to a different account with a GET request:
A hacker could just send an HTTP request to the server saying GET /transfer?amount=$1000000&account-to=999999
, right?
Wrong. The hackers attack won't work. The server will basically think?
Huh? Who is this guy trying to initiate a transfer. It's not the owner of the account, that's for sure.
How does the server know this? Because there's no session_id
cookie authenticating the requester.
When you sign in with your username and password, the server sets a session_id
cookie on your browser. That way, you don't have to authenticate each request with your username and password. When your browser sends the session_id
cookie, the server knows:
Oh, that's John Doe. He signed in successfully 2.5 minutes ago. He's good to go.
A hacker might think:
Hmm. A normal HTTP request won't work, but if I could get my hand on that
session_id
cookie, I'd be golden.
The users browser has a bunch of cookies set for the bank.com
domain. Every time the user makes a request to the bank.com
domain, all of the cookies get sent along. Including the session_id
cookie.
So if a hacker could get you to make the GET request that transfers money into his account, he'd be successful. How could he trick you into doing so? With Cross Site Request Forgery.
It's pretty simply, actually. The hacker could just get you to visit his website. On his website, he could have the following image tag:
<img src="http://bank.com/transfer?amount=$1000000&account-to=999999">
When the users browser comes across that image tag, it'll be making a GET request to that url. And since the request comes from his browser, it'll send with it all of the cookies associated with bank.com
. If the user had recently signed in to bank.com
... the session_id
cookie will be set, and the server will think that the user meant to transfer $1,000,000 to account 999999!
Well, just don't visit dangerous sites and you'll be fine.
That isn't enough. What if someone posts that image to Facebook and it appears on your wall? What if it's injected into a site you're visiting with a XSS attack?
It's not so bad. Only GET requests are vulnerable.
Not true. A form that sends a POST request can be dynamically generated. Here's the example from the Rails Guide on Security:
<a href="http://www.harmless.com/" onclick="
var f = document.createElement('form');
f.style.display = 'none';
this.parentNode.appendChild(f);
f.method = 'POST';
f.action = 'http://www.example.com/account/destroy';
f.submit();
return false;">To the harmless survey</a>
When your ApplicationController
has this:
protect_from_forgery with: :exception
This:
<%= form_tag do %>
Form contents
<% end %>
Is compiled into this:
<form accept-charset="UTF-8" action="/" method="post">
<input name="utf8" type="hidden" value="✓" />
<input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" />
Form contents
</form>
In particular, the following is generated:
<input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" />
To protect against CSRF attacks, if Rails doesn't see the authenticity token sent along with a request, it won't consider the request safe.
How is an attacker supposed to know what this token is? A different value is generated randomly each time the form is generated:
A Cross Site Scripting (XSS) attack - that's how. But that's a different vulnerability for a different day.
I prefer to have the server return the date without modification, and have javascript do the view massaging. My API returns "MM/DD/YYYY hh:mm:ss" from SQL Server.
Resource
angular.module('myApp').factory('myResource',
function($resource) {
return $resource('api/myRestEndpoint/', null,
{
'GET': { method: 'GET' },
'QUERY': { method: 'GET', isArray: true },
'POST': { method: 'POST' },
'PUT': { method: 'PUT' },
'DELETE': { method: 'DELETE' }
});
}
);
Controller
var getHttpJson = function () {
return myResource.GET().$promise.then(
function (response) {
if (response.myDateExample) {
response.myDateExample = $filter('date')(new Date(response.myDateExample), 'M/d/yyyy');
};
$scope.myModel= response;
},
function (response) {
console.log(response.data);
}
);
};
myDate Validation Directive
angular.module('myApp').directive('myDate',
function($window) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
var moment = $window.moment;
var acceptableFormats = ['M/D/YYYY', 'M-D-YYYY'];
function isDate(value) {
var m = moment(value, acceptableFormats, true);
var isValid = m.isValid();
//console.log(value);
//console.log(isValid);
return isValid;
};
ngModel.$parsers.push(function(value) {
if (!value || value.length === 0) {
return value;
};
if (isDate(value)) {
ngModel.$setValidity('myDate', true);
} else {
ngModel.$setValidity('myDate', false);
}
return value;
});
}
}
}
);
HTML
<div class="form-group">
<label for="myDateExample">My Date Example</label>
<input id="myDateExample"
name="myDateExample"
class="form-control"
required=""
my-date
maxlength="50"
ng-model="myModel.myDateExample"
type="text" />
<div ng-messages="myForm.myDateExample.$error" ng-if="myForm.$submitted || myForm.myDateExample.$touched" class="errors">
<div ng-messages-include="template/validation/messages.html"></div>
</div>
</div>
template/validation/messages.html
<div ng-message="required">Required Field</div>
<div ng-message="number">Must be a number</div>
<div ng-message="email">Must be a valid email address</div>
<div ng-message="minlength">The data entered is too short</div>
<div ng-message="maxlength">The data entered is too long</div>
<div ng-message="myDate">Must be a valid date</div>
I get this error when my project .net framework version does not match the framework version of the DLL I am linking to. In my case, I was getting:
"The type or namespace name 'UserVoice' could not be found (are you missing a using directive or an assembly reference?).
UserVoice was .Net 4.0, and my project properties were set to ".Net 4.0 Client Profile". Changing to .Net 4.0 on the project cleared the error. I hope this helps someone.
You can use .equals
for columns or entire dataframes.
df['col1'].equals(df['col2'])
If they're equal, that statement will return True
, else False
.
To delete all the records except te last N you may use the query reported below.
It's a single query but with many statements so it's actually not a single query the way it was intended in the original question.
Also you need a variable and a built-in (in the query) prepared statement due to a bug in MySQL.
Hope it may be useful anyway...
nnn are the rows to keep and theTable is the table you're working on.
I'm assuming you have an autoincrementing record named id
SELECT @ROWS_TO_DELETE := COUNT(*) - nnn FROM `theTable`;
SELECT @ROWS_TO_DELETE := IF(@ROWS_TO_DELETE<0,0,@ROWS_TO_DELETE);
PREPARE STMT FROM "DELETE FROM `theTable` ORDER BY `id` ASC LIMIT ?";
EXECUTE STMT USING @ROWS_TO_DELETE;
The good thing about this approach is performance: I've tested the query on a local DB with about 13,000 record, keeping the last 1,000. It runs in 0.08 seconds.
The script from the accepted answer...
DELETE FROM `table`
WHERE id NOT IN (
SELECT id
FROM (
SELECT id
FROM `table`
ORDER BY id DESC
LIMIT 42 -- keep this many records
) foo
);
Takes 0.55 seconds. About 7 times more.
Test environment: mySQL 5.5.25 on a late 2011 i7 MacBookPro with SSD
One line if:
<statement> if <condition>
Your case:
"Yes" if @item.rigged
"No" if [email protected] # or: "No" unless @item.rigged
Here's a function to see what the effective SQL will be, adpated from a comment by "Mark" at php.net:
function sql_debug($sql_string, array $params = null) {
if (!empty($params)) {
$indexed = $params == array_values($params);
foreach($params as $k=>$v) {
if (is_object($v)) {
if ($v instanceof \DateTime) $v = $v->format('Y-m-d H:i:s');
else continue;
}
elseif (is_string($v)) $v="'$v'";
elseif ($v === null) $v='NULL';
elseif (is_array($v)) $v = implode(',', $v);
if ($indexed) {
$sql_string = preg_replace('/\?/', $v, $sql_string, 1);
}
else {
if ($k[0] != ':') $k = ':'.$k; //add leading colon if it was left out
$sql_string = str_replace($k,$v,$sql_string);
}
}
}
return $sql_string;
}
string input = "America.USA"
string output = input.Substring(input.IndexOf('.') + 1);
If the position of the element containing the Lorum Ipsum is set absolute, you can specify the position via CSS. The "here" and "and here" elements would need to be contained in a block level element. I'll use markup like this.
print("<div id="lipsum">");
print("<div id="here">");
print(" here");
print("</div>");
print("<div id="andhere">");
print("and here");
print("</div>");
print("blah");
print("</div>");
Here's the CSS for above.
#lipsum {position:absolute;top:0;left:0;} /* example */ #here {position:absolute;top:0;right:0;} #andhere {position:absolute;bottom:0;right:0;}
Again, the above only works (reliably) if #lipsum is positioned via absolute.
If not, you'll need to use the float property.
#here, #andhere {float:right;}
You'll also need to put your markup in the appropriate place. For better presentation, your two divs will probably need some padding and margins so that the text doesn't all run together.
I had the same issue and realized that removing the parentheses worked. Sometimes having someone else read your code can be useful if you have been the only one working on it for some time.
E.g.
cmd.CommandType = CommandType.Text();
Replace: cmd.CommandType = CommandType.Text;
There is a JDK socket tutorial here, which covers both the server and client end. That looks exactly like what you want.
(from that tutorial) This sets up to read from an echo server:
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
taking a stream of bytes and converts to strings via the reader and using a default encoding (not advisable, normally).
Error handling and closing sockets/streams omitted from the above, but check the tutorial.
You can pass a regular expression to the text parameter of findAll
, like so:
import BeautifulSoup
import re
columns = soup.findAll('td', text = re.compile('your regex here'), attrs = {'class' : 'pos'})
You have to use a Class
instance because of the generic type erasure during compilation.
public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
try {
return clazz.cast(o);
} catch(ClassCastException e) {
return null;
}
}
The declaration of that method is:
public T cast(Object o)
This can also be used for array types. It would look like this:
final Class<int[]> intArrayType = int[].class;
final Object someObject = new int[]{1,2,3};
final int[] instance = convertInstanceOfObject(someObject, intArrayType);
Note that when someObject
is passed to convertToInstanceOfObject
it has the compile time type Object
.
Just include following in your code
<body background="C:\Users\Desktop\images.jpg">
if you want to specify the size and opacity you can use following
<p><img style="opacity:0.9;" src="C:\Users\Desktop\images.jpg" width="300" height="231" alt="Image" /></p>
According to DOM level 4 specs, which is the current version in development, there are some new handy mutation methods available: append()
, prepend()
, before()
, after()
, replace()
, and remove()
.
https://catalin.red/removing-an-element-with-plain-javascript-remove-method/
It's a class that cannot be instantiated, and forces implementing classes to, possibly, implement abstract methods that it outlines.
If you do not have the ability to modify your php.ini file, use cURL: PHP Curl And Cookies
Here is an example function I created:
function get_web_page( $url, $cookiesIn = '' ){
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, //return headers in addition to content
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLINFO_HEADER_OUT => true,
CURLOPT_SSL_VERIFYPEER => true, // Validate SSL Cert
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_COOKIE => $cookiesIn
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$rough_content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header_content = substr($rough_content, 0, $header['header_size']);
$body_content = trim(str_replace($header_content, '', $rough_content));
$pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m";
preg_match_all($pattern, $header_content, $matches);
$cookiesOut = implode("; ", $matches['cookie']);
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['headers'] = $header_content;
$header['content'] = $body_content;
$header['cookies'] = $cookiesOut;
return $header;
}
NOTE: In revisiting this function I noticed that I had disabled SSL checks in this code. That is generally a BAD thing even though in my particular case the site I was using it on was local and was safe. As a result I've modified this code to have SSL checks on by default. If for some reason you need to change that, you can simply update the value for CURLOPT_SSL_VERIFYPEER, but I wanted the code to be secure by default if someone uses this.
Guessing from the information I have, you're not actually compiling the program, but trying to run it. That is, ALL_BUILD is set as your startup project. (It should be in a bold font, unlike the other projects in your solution) If you then try to run/debug, you will get the error you describe, because there is simply nothing to run.
The project is most likely generated via CMAKE and included in your Visual Studio solution. Set any of the projects that do generate a .exe as the startup project (by right-clicking on the project and selecting "set as startup project") and you will most likely will be able to start those from within Visual Studio.
This keyExists(key, search)
can be used to easily lookup a key within objects or arrays!
Just pass it the key you want to find, and search obj (the object or array) you want to find it in.
function keyExists(key, search) {_x000D_
if (!search || (search.constructor !== Array && search.constructor !== Object)) {_x000D_
return false;_x000D_
}_x000D_
for (var i = 0; i < search.length; i++) {_x000D_
if (search[i] === key) {_x000D_
return true;_x000D_
}_x000D_
}_x000D_
return key in search;_x000D_
}_x000D_
_x000D_
// How to use it:_x000D_
// Searching for keys in Arrays_x000D_
console.log(keyExists('apple', ['apple', 'banana', 'orange'])); // true_x000D_
console.log(keyExists('fruit', ['apple', 'banana', 'orange'])); // false_x000D_
_x000D_
// Searching for keys in Objects_x000D_
console.log(keyExists('age', {'name': 'Bill', 'age': 29 })); // true_x000D_
console.log(keyExists('title', {'name': 'Jason', 'age': 29 })); // false
_x000D_
It's been pretty reliable and works well cross-browser.
Some dude has come up with a smart preprocessor idea in this post
Starting Scala 2.13
, the groupMapReduce method does that in one pass through the list:
// val seq = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
seq.groupMapReduce(identity)(_ => 1)(_ + _)
// immutable.Map[String,Int] = Map(banana -> 1, oranges -> 3, apple -> 3)
seq.groupMapReduce(identity)(_ => 1)(_ + _)("apple")
// Int = 3
This:
group
s list elements (group part of groupMapReduce)
map
s each grouped value occurrence to 1 (map part of groupMapReduce)
reduce
s values within a group of values (_ + _
) by summing them (reduce part of groupMapReduce).
This is a one-pass version of what can be translated by:
seq.groupBy(identity).mapValues(_.map(_ => 1).reduce(_ + _))
Working with Subclipse on Eclipse Indigo Service Release 2
I had commited folders with temporary files and logs lying under /src to the SVN repository. And after realizing it, I found myself in the same situation with a grayed out "svn:ignore"
I found following solution:
1. I deleted the folder from my Project Source
2. Team -> Commit... withouth the folder
3. Recreated the folder back into the project tree
Now I was able to use "Team -> Add to svn:ignore..."
simple difference between for and foreach
for loop is working with values.it must have condition then increment and intialization also.you have to knowledge about 'how many times loop repeated'.
foreach is working with objects and enumaretors. no need to knowledge how many times loop repeated.
The only way I could solve it was via:
org.glassfish.jersey.core jersey-server ${jersey-2-version}
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey-2-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey-2-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>${jersey-2-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>${jersey-2-version}</version>
</dependency>
So, only if I added jersey-container-servlet
and jersey-hk2
would it run without errors
SELECT ... HAVING ...
is a good start. Not many developers seem to understand how to use it.
I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".
It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.
Share a Controller
Two directives can use the same controller by passing the same method to two directives, like so:
app.controller( 'MyCtrl', function ( $scope ) {
// do stuff...
});
app.directive( 'directiveOne', function () {
return {
controller: 'MyCtrl'
};
});
app.directive( 'directiveTwo', function () {
return {
controller: 'MyCtrl'
};
});
Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.
Require a Controller
If you want to share the same instance of a controller, then you use require
.
require
ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel
.
^require
, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.
In either event, you have to use the two directives together for this to work. require
is a way of communicating between components.
Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive
To handle the possibility of int
, float
, and empty string values, I'd use a combination of a list comprehension, dictionary comprehension, along with conditional expressions, as shown:
dicts = [{'a': '1' , 'b': '' , 'c': '3.14159'},
{'d': '4' , 'e': '5' , 'f': '6'}]
print [{k: int(v) if v and '.' not in v else float(v) if v else None
for k, v in d.iteritems()}
for d in dicts]
# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]
However dictionary comprehensions weren't added to Python 2 until version 2.7. It can still be done in earlier versions as a single expression, but has to be written using the dict
constructor like the following:
# for pre-Python 2.7
print [dict([k, int(v) if v and '.' not in v else float(v) if v else None]
for k, v in d.iteritems())
for d in dicts]
# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]
Note that either way this creates a new dictionary of lists, instead of modifying the original one in-place (which would need to be done differently).
Concatenation you say? How about #concat
method then?
a = 'foo'
a.object_id #=> some number
a.concat 'bar' #=> foobar
a.object_id #=> same as before -- string a remains the same object
In all fairness, concat
is aliased as <<
.
first, create a class to hold your parameters:
public class PkRk {
public int pk { get; set; }
public int rk { get; set; }
}
then, use the Html.Action
passing the parameters:
Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })
and use in Controller:
public ActionResult PkRkAction(PkRk pkrk) {
return PartialView(pkrk);
}
This is not something that SVG 1.1 supports. SVG 1.2 does have the textArea
element, with automatic word wrapping, but it's not implemented in all browsers. SVG 2 does not plan on implementing textArea
, but it does have auto-wrapped text.
However, given that you already know where your linebreaks should occur, you can break your text into multiple <tspan>
s, each with x="0"
and dy="1.4em"
to simulate actual lines of text. For example:
<g transform="translate(123 456)"><!-- replace with your target upper left corner coordinates -->
<text x="0" y="0">
<tspan x="0" dy="1.2em">very long text</tspan>
<tspan x="0" dy="1.2em">I would like to linebreak</tspan>
</text>
</g>
Of course, since you want to do that from JavaScript, you'll have to manually create and insert each element into the DOM.
I think the NOBR tag might be overkill, and as you said, unreliable.
There are 2 options available depending on how you are displaying the text.
If you are displaying text in a table cell you would do Long Text Here. If you are using a div or a span, you can use the style="white-space: nowrap;"
Open file/etc/nginx/nginx.conf
Add or change client_max_body_size 0;
A new option is Jexus Manager for IIS Express,
https://blog.lextudio.com/2014/10/jexus-manager-for-iis-express/
It is just the management tool you know how to use.
Set the style on the textbox as text-transform: uppercase?
According your condition, you can also define some environmental variables, and fetch it via ENV['some-var']
in ruby code, this solution may not fit for you, but I hope it may help others.
Example: you can create different files .development_env
, .production_env
, .test_env
and load it according your application environments, check this gen dotenv-rails which automate this for your.
I would use a decimal with the proper precision for your data.
The grid system in Bootstrap 3 requires a bit of a lateral shift in your thinking from Bootstrap 2. A column in BS2 (col-*
) is NOT synonymous with a column in BS3 (col-sm-*
, etc), but there is a way to achieve the same result.
Check out this update to your fiddle: http://jsfiddle.net/pjBzY/22/ (code copied below).
First of all, you don't need to specify a col for each screen size if you want 50/50 columns at all sizes. col-sm-6
applies not only to small screens, but also medium and large, meaning class="col-sm-6 col-md-6"
is redundant (the benefit comes in if you want to change the column widths at different size screens, such as col-sm-6 col-md-8
).
As for the margins issue, the negative margins provide a way to align blocks of text in a more flexible way than was possible in BS2. You'll notice in the jsfiddle, the text in the first column aligns visually with the text in the paragraph outside the row
-- except at "xs" window sizes, where the columns aren't applied.
If you need behavior closer to what you had in BS2, where there is padding between each column and there are no visual negative margins, you will need to add an inner-div to each column. See the inner-content
in my jsfiddle. Put something like this in each column, and they will behave the way old col-*
elements did in BS2.
jsfiddle HTML
<div class="container">
<p class="other-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquam sed sem nec viverra. Phasellus fringilla metus vitae libero posuere mattis. Integer sit amet tincidunt felis. Maecenas et pharetra leo. Etiam venenatis purus et nibh laoreet blandit.</p>
<div class="row">
<div class="col-sm-6 my-column">
Col 1
<p class="inner-content">Inner content - THIS element is more synonymous with a Bootstrap 2 col-*.</p>
</div>
<div class="col-sm-6 my-column">
Col 2
</div>
</div>
</div>
and the CSS
.row {
border: blue 1px solid;
}
.my-column {
background-color: green;
padding-top: 10px;
padding-bottom: 10px;
}
.my-column:first-child {
background-color: red;
}
.inner-content {
background: #eee;
border: #999;
border-radius: 5px;
padding: 15px;
}
string nomFile = "9quali52ty3";
byte[] nomBytes = Encoding.ASCII.GetBytes(nomFile);
string name = "";
foreach (byte he in nomBytes)
{
name += he.ToString("X02");
}
`
Console.WriteLine(name);
// it's` better now ;)
To the column you want ordering keep "sType": "date-uk"
for example:-"data": "OrderDate", "sType": "date-uk"
After the completion of Datatable script in ajax keep the below code
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"date-uk-pre": function (a) {
var ukDatea = a.split('/');
return (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
},
"date-uk-asc": function (a, b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"date-uk-desc": function (a, b) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
Then You will get date as 22-10-2018 in this format
@Alexander
's solution is the one which I was looking for.
But it was causing an error - TypeError: a.stopPropagation is not a function
.
So I made the event with KeyboardEvent
.
Here's the working code and Javascript version is very convenient for React.js projects. I also used this for my React.js project.
(function selectFirst(input) {
let _addEventListener = input.addEventListener
? input.addEventListener
: input.attachEvent;
function addEventListenerWrapper(type, listener) {
if (type === 'keydown') {
console.log('keydown');
let orig_listener = listener;
listener = event => {
let suggestion_selected =
document.getElementsByClassName('pac-item-selected').length > 0;
if (event.keyCode === 13 && !suggestion_selected) {
let simulated_downarrow = new KeyboardEvent('keydown', {
bubbles: true,
cancelable: true,
keyCode: 40
});
orig_listener.apply(input, [simulated_downarrow]);
}
orig_listener.apply(input, [event]);
};
}
_addEventListener.apply(input, [type, listener]);
}
if (input.addEventListener) input.addEventListener = addEventListenerWrapper;
else if (input.attachEvent) input.attachEvent = addEventListenerWrapper;
})(addressInput);
this.autocomplete = new window.google.maps.places.Autocomplete(addressInput, options);
Hope this can help someone, :)
Listing all the databases in mongoDB console is using the command show dbs
.
For more information on this, refer the Mongo Shell Command Helpers that can be used in the mongo shell.
Imagine you are in a bank, trying to get some money out of your account. But it's dark; the bank is pitch black: there's no light and you can't see your hand in front of your face. You are surrounded by another 20 people. They all look the same. And everybody has the same voice. And everyone is a potential bad guy. In other words, HTTP is stateless.
This bank is a funny type of bank - for the sake of argument here's how things work:
The teller can't see or readily recognise you, remember, because the lights are all out. What if your teller gives your $10,000 withdrawal to someone else - the wrong person?! It's absolutely vital that the teller can recognise you as the one who made the withdrawal, so that you can get the money (or resource) that you asked for.
Solution:
When you first appear to the teller, he or she tells you something in secret:
"When ever you are talking to me," says the teller, "you should first identify yourlself as GNASHEU329 - that way I know it's you".
Nobody else knows the secret passcode.
So I decide to go to and chill out for 20 minutes and then later i go to the teller and say "I'd like to collect my withdrawal"
The teller asks me: "who are you??!"
"It's me, Mr George Banks!"
"Prove it!"
And then I tell them my passcode: GNASHEU329
"Certainly Mr Banks!"
That basically is how a session works. It allows one to be uniquely identified in a sea of millions of people. You need to identify yourself every time you deal with the teller.
If you got any questions or are unclear - please post comment and i will try to clear it up for you. The following is not strictly speaking, completely accurate in its terminology, but I hope it's helpful to you in understanding concepts.
If you remember which branch was checked out before (e.g. master
) you could simply
git checkout master
to get out of detached HEAD state.
Generally speaking: git checkout <branchname>
will get you out of that.
If you don't remember the last branch name, try
git checkout -
This also tries to check out your last checked out branch.
for (NSString* key in xyz) {
id value = xyz[key];
// do stuff
}
This works for every class that conforms to the NSFastEnumeration protocol (available on 10.5+ and iOS), though NSDictionary
is one of the few collections which lets you enumerate keys instead of values. I suggest you read about fast enumeration in the Collections Programming Topic.
Oh, I should add however that you should NEVER modify a collection while enumerating through it.
I had this error when I tried to update npm, but had a really old version (1.3.6 !) installed from yum in AWS Linux. I was able to manually install a newer npm version and everything was remedied.
I found that I was getting an error "cannot provide arguments when creating an instance of type parameter T" so I needed to do this:
var x = Activator.CreateInstance(typeof(T), args) as T;
There's this Explorer Exclude extension that exactly does this. https://marketplace.visualstudio.com/items?itemName=RedVanWorkshop.explorer-exclude-vscode-extension
It adds an option to hide current folder/file to the right click menu. It also adds a vertical tab Hidden Items to explorer menu where you can see currently hidden files & folders and can toggle them easily.
There are three ways to add your filter,
@Component
@Bean
with Filter
type in Spring @Configuration
@Bean
with FilterRegistrationBean
type in Spring @Configuration
Either #1 or #2 will do if you want your filter applies to all requests without customization, use #3 otherwise. You don't need to specify component scan for #1 to work as long as you place your filter class in the same or sub-package of your SpringApplication
class. For #3, use along with #2 is only necessary when you want Spring to manage your filter class such as have it auto wired dependencies. It works just fine for me to new my filter which doesn't need any dependency autowiring/injection.
Although combining #2 and #3 works fine, I was surprised it doesn't end up with two filters applying twice. My guess is that Spring combines the two beans as one when it calls the same method to create both of them. In case you want to use #3 alone with authowiring, you can AutowireCapableBeanFactory
. The following is an example,
private @Autowired AutowireCapableBeanFactory beanFactory;
@Bean
public FilterRegistrationBean myFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
Filter myFilter = new MyFilter();
beanFactory.autowireBean(myFilter);
registration.setFilter(myFilter);
registration.addUrlPatterns("/myfilterpath/*");
return registration;
}
.parent {
width: 500px;
height: 200px;
border: 2px solid #000;
display: table-cell;
vertical-align: middle;
}
#kid {
width:70%; /* 70% of the parent */
margin:auto;
border:2px solid #F00;
height: 70%;
}
This does solve the problem very well (tested in all new browsers), where the parent div has class="parent" and the child div has id="kid".
That style centers both horizontally and vertically. Vertical center can only be done using complicated tricks--or by making the parent div function as a table-cell, which is one of the only elements in HTML that properly supports vertical alignment.
Simply set the height of the kid, margin auto, and middle vertical alignment, and it will work. It's the easiest solution that I know.
is there a better syntax?
No. CSS' or
operator (,
) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c
.
If the Toggle Visual Space
icon shall be added to a Visual Studio toolbar of your choice, because it shall be turned on and off via mouse click, then follow this instruction:
Customize the desired toolbar
Click on Customize...
Click on Add Command...
Go to Edit
and chose Toggle Visual Space
Click on OK
Tested with Visual Studio 2019.
Try this, at the end of the each loop, ids array will contain all the hexcodes.
var ids = [];
$(document).ready(function($) {
var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
$(".color_cell").each(function() {
code = $(this).attr('id');
ids.push(code);
$div.append(code + "<br />");
});
});
I have a bash script that calls a small python routine to display a message window. As I need to use killall to stop the python script I can't use the above method as it would then mean running killall python which could take out other python programmes so I use
pythonprog.py "$argument"
& # The & returns control straight to the bash script so must be outside the backticks. The preview of this message is showing it without "`" either side of the command for some reason.
As long as the python script will run from the cli by name rather than python pythonprog.py this works within the script. If you need more than one argument just use a space between each one within the quotes.
The rename method has gained an axis parameter to match most of the rest of the pandas API.
So, in addition to this:
df.rename(columns = {'two':'new_name'})
You can do:
df.rename({'two':'new_name'}, axis=1)
or
df.rename({'two':'new_name'}, axis='columns')
With CMake, it's generally recommended to do an "out of source" build. Create your CMakeLists.txt
in the root of your project. Then from the root of your project:
mkdir Release
cd Release
cmake -DCMAKE_BUILD_TYPE=Release ..
make
And for Debug
(again from the root of your project):
mkdir Debug
cd Debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
make
Release
/ Debug
will add the appropriate flags for your compiler. There are also RelWithDebInfo
and MinSizeRel
build configurations.
You can modify/add to the flags by specifying a toolchain file in which you can add CMAKE_<LANG>_FLAGS_<CONFIG>_INIT
variables, e.g.:
set(CMAKE_CXX_FLAGS_DEBUG_INIT "-Wall")
set(CMAKE_CXX_FLAGS_RELEASE_INIT "-Wall")
See CMAKE_BUILD_TYPE for more details.
As for your third question, I'm not sure what you are asking exactly. CMake should automatically detect and use the compiler appropriate for your different source files.
EDIT: Updated for jQuery 1.8
jQuery 1.8 will add browser specific transformations. jsFiddle Demo
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: Added code to make it a jQuery function.
For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.
Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.
Here is a jsFiddle.
If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.
HTML
<div class="rotate">
<h1>Rotatey text</h1>
</div>
CSS
/* Totally for style */
.rotate {
background: #F02311;
color: #FFF;
width: 200px;
height: 200px;
text-align: center;
font: normal 1em Arial;
position: relative;
top: 50px;
left: 50px;
}
/* The real code */
.rotated {
-webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */
-moz-transform: rotate(45deg); /* Firefox 3.5-15 */
-ms-transform: rotate(45deg); /* IE 9 */
-o-transform: rotate(45deg); /* Opera 10.50-12.00 */
transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.10+ */
}
jQuery
Make sure these are wrapped in $(document).ready
$('.rotate').click(function() {
$(this).toggleClass('rotated');
});
Custom intervals
var rotation = 0;
$('.rotate').click(function() {
rotation += 5;
$(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
'-moz-transform' : 'rotate('+ rotation +'deg)',
'-ms-transform' : 'rotate('+ rotation +'deg)',
'transform' : 'rotate('+ rotation +'deg)'});
});
This helped for me for connecting to AWS MYSQL(RDS) from python 3.x based lambda function and loading into a pandas DataFrame
import json
import boto3
import pymysql
import pandas as pd
user = 'username'
password = 'XXXXXXX'
client = boto3.client('rds')
def lambda_handler(event, context):
conn = pymysql.connect(host='xxx.xxxxus-west-2.rds.amazonaws.com', port=3306, user=user, passwd=password, db='database name', connect_timeout=5)
df= pd.read_sql('select * from TableName limit 10',con=conn)
print(df)
# TODO implement
#return {
# 'statusCode': 200,
# 'df': df
#}
There's no single method to do that. Use this:
@SuppressWarnings("unchecked")
public static <T extends Comparable> List<T> asSortedList(Collection<T> collection) {
T[] array = collection.toArray(
(T[])new Comparable[collection.size()]);
Arrays.sort(array);
return Arrays.asList(array);
}
Without VBA...
If you can use a helper column, you can use the MATCH
function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match
To simply identify duplicates, use a helper column
Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:
=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")
Drag/copy this forumla down, and it should identify the duplicates.
To highlight cells, use conditional formatting:
With some tinkering, you can use this MATCH
function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.
Something like:
=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))
For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:
=B1="Duplicate"
This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.
These days I am diving into scheme, and now I think am good at recursing and eval. HAHAHA. Just share some new ways:
first ,eval it
print eval('string%s' % (''.join(['.replace("%s","")'%i for i in replace_list])))
second , recurse it
def repn(string,replace_list):
if replace_list==[]:
return string
else:
return repn(string.replace(replace_list.pop(),""),replace_list)
print repn(string,replace_list)
Hey ,don't downvote. I am just want to share some new idea.
It depends on the problem.
You may also consider the ToolStripButton control if you don't mind hosting it in a ToolStripContainer. I think it can natively support pressed and unpressed states.
Example for select an option from the drop down list:
Click on drop down list by using id or csspath or xpath or name. I have used id here.
driver.findElement(By.id("dropdownlistone")).click(); // To click on drop down list
driver.findElement(By.linkText("india")).click(); // To select a data from the drop down list.
As a programmer often on the client-end, I prefer the query argument. Also, for me, it separates the URL path from the parameters, adds to clarity, and offers more extensibility. It also allows me to have separate logic between the URL/URI building and the parameter builder.
I do like what manuel aldana said about the other option if there's some sort of tree involved. I can see user-specific parts being treed off like that.
What works for me was org.mockito.ArgumentMatchers.isA
for example:
isA(long[].class)
that works fine.
the implementation difference of each other is:
public static <T> T any(Class<T> type) {
reportMatcher(new VarArgAware(type, "<any " + type.getCanonicalName() + ">"));
return Primitives.defaultValue(type);
}
public static <T> T isA(Class<T> type) {
reportMatcher(new InstanceOf(type));
return Primitives.defaultValue(type);
}
That might happen because the pojos you are using lack of the precise constructor the service needs. That is, try to generate all the constructors for the pojo or objects (model object) that your serviceClient uses, so that the client can be instanced correctly. In your case,regenerate the constructors (with arguments)for your client object (taht is your model object).
Just remove white space of all folders present in the given path for example Program Files You can remove it by following steps-> Open elevated cmd, In the command prompt execute: mklink /J C:\Program-Files "C:\Program Files" This will remove space and replace it with "-". Better do this with both sdk and jdk path. This works :)
I've been testing alternatives to C# Web browser component for few days now and here is my list:
1. Using newer IE versions 8,9:
Web Browser component is IE7 not IE8? How to change this?
Pros:
Cons:
This doesn't require much work and you can get some HTML5 and CSS3 support although IE9 lacks some of best CSS3 and HTML5 features. But I'm sure you could get IE10 running same way. The problem would be that target system would have to have IE10 installed, and since is still in preview on Windows 7 I would suggest against it.
OpenWebKitSharp is a .net wrapper for the webkit engine based on the WebKit.NET 0.5 project. WebKit is a layout engine used by Chrome/Safari
Pros:
Cons:
OpenWebKit is quite nice although many features are not yet implemented, I experienced few issues using it with visual studio which throws null object reference here and then in design mode, there are some js problems. Everyone using it will almost immediately notice js alert does nothing. Events like mouseup,mousedown... etc. doesn't work, js drag and drop is buggy and so on..
I also had some difficulties installing it since it requires specific version of VC redistributable installed, so after exception I looked at event log, found version of VC and installed it.
3. GeckoFX
Pros:
Cons:
GeckoFX is a cross platform Webrowser control for embedding into WinForms Applications. This can be used with .NET on Windows and with mono on Linux. Gecko is a layout engine used by Firefox.
I bumped into few information that GeckoFX is not actively developed which is not true, of course it's always one or two versions behind of Firefox but that is normal, I was really impressed by activity and the control itself. It does everything I needed, but I needed some time to get it running, here's a little tutorial to get it running:
If your really must use Chrome, take a look at this product called Awesomium, it's free for non-commercial projects, but license is few thousand dollars for commercial.
You need a ResourceLink in your META-INF/context.xml
file to make the global resource available to the web application.
<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
type="javax.sql.DataSource" />
It is not possible at this point (unless the author of the image explicitly included the Dockerfile).
However, it is definitely something useful! There are two things that will help to obtain this feature.
Worked for me:
Just delete the node-sass folder and run npm install
.
With PowerShell, go to the path where your files are and then type this command and replace ENTER THE STRING YOU SEARCH HERE
(but keep the double quotes):
findstr /S /I /M /C:"ENTER THE STRING YOU SEARCH HERE" *.*
Have a nice day
char* str=NULL;
int len = asprintf(&str, "%g", float_var);
if (len == -1)
fprintf(stderr, "Error converting float: %m\n");
else
printf("float is %s\n", str);
free(str);
var from = $("#datepicker").val();
var f = $.datepicker.parseDate("d-m-Y", from);
The setting for the list throttle
For addtional reading: http://blogs.msdn.com/b/dinaayoub/archive/2010/04/22/sharepoint-2010-how-to-change-the-list-view-threshold.aspx
For me CSS solutions didn't work. But setting the width programmatically does the job. On iframe load set the width programmatically:
$('iframe').width('100%');
For all tracked unstaged files use:
git checkout -- .
The .
at the end is important.
You can replace .
with a sub-directory name to clear only a specific sub-directory of your project. The problem is addressed specifically here.
There is not only 1 %SystemRoot%\System32
on Windows x64. There are 2 such directories.
The real %SystemRoot%\System32
directory is for 64-bit applications. This directory contains a 64-bit cmd.exe
.
But there is also %SystemRoot%\SysWOW64
for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32
. It contains a 32-bit cmd.exe
.
32-bit applications can access %SystemRoot%\System32
for 64-bit applications by using the alias %SystemRoot%\Sysnative
in path.
For more details see the Microsoft documentation about File System Redirector.
So the subdirectory run
was created either in %SystemRoot%\System32
for 64-bit applications and 32-bit cmd
is run for which this directory does not exist because there is no subdirectory run
in %SystemRoot%\SysWOW64
which is %SystemRoot%\System32
for 32-bit cmd.exe
or the subdirectory run
was created in %SystemRoot%\System32
for 32-bit applications and 64-bit cmd
is run for which this directory does not exist because there is no subdirectory run
in %SystemRoot%\System32
as this subdirectory exists only in %SystemRoot%\SysWOW64
.
The following code could be used at top of the batch file in case of subdirectory run
is in %SystemRoot%\System32
for 64-bit applications:
@echo off
set "SystemPath=%SystemRoot%\System32"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"
Every console application in System32\run
directory must be executed with %SystemPath%
in the batch file, for example %SystemPath%\run\YourApp.exe
.
How it works?
There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32
as defined at top.
But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative
. In this case the batch file is processed currently by 32-bit cmd.exe
and only in this case %SystemRoot%\Sysnative
needs to be used at all. Otherwise %SystemRoot%\System32
can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe
, this is the directory containing the 64-bit console applications (and the subdirectory run
).
Note: %SystemRoot%\Sysnative
is not a directory! It is not possible to cd
to %SystemRoot%\Sysnative
or use if exist %SystemRoot%\Sysnative
or if exist %SystemRoot%\Sysnative\
. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe
or more general if exist %SystemRoot%\Sysnative\*
.
size: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]),
Learn more: Typechecking With PropTypes
This answer on super user I think is a better answer. From https://superuser.com/a/573761/67952
"But since you asked for a way without using Before and After, you can use:
Type=idle
which as man systemd.service
explains
Behavior of idle is very similar to simple; however, actual execution of the service program is delayed until all active jobs are dispatched. This may be used to avoid interleaving of output of shell services with the status output on the console. Note that this type is useful only to improve console output, it is not useful as a general unit ordering tool, and the effect of this service type is subject to a 5s time-out, after which the service program is invoked anyway. "
You need DATE_ADD/DATE_SUB
:
AND v.date > (DATE_SUB(CURDATE(), INTERVAL 2 MONTH))
AND v.date < (DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
should work.
A slight generalization to Alexander's answer - np.reshape can take -1 as an argument, meaning "total array size divided by product of all other listed dimensions":
e.g. to flatten all but the last dimension:
>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000, 25)
The json.load() method (without "s" in "load") can read a file directly:
import json
with open('strings.json') as f:
d = json.load(f)
print(d)
json.loads() method, which is used for string arguments only.
import json
person = '{"name": "Bob", "languages": ["English", "Fench"]}'
print(type(person))
# Output : <type 'str'>
person_dict = json.loads(person)
print( person_dict)
# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}
print(type(person_dict))
# Output : <type 'dict'>
Here , we can see after using loads() takes a string ( type(str) ) as a input and return dictionary.
I have created a libray for pick image from camera or galley and cropping also
Try this,
ImagePro.Java
public class ImagePro
{
public static String TAG = "ImagePro";
Activity activity;
Uri mImageCaptureUri;
public static int CAMERA_CODE = 64;
public static int GALLERY_CODE = 74;
public static int CROPPING_CODE = 84;
private final static int REQUEST_PERMISSION_REQ_CODE = 704;
public ImagePro(Activity activity) {
this.activity = activity;
this.outPutFile = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_REQ_CODE);
}
}
private void LogToast(String message) {
try {
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Log.d(TAG, message);
}
private void Toast(String message) {
try {
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
private void Log(String message) {
Log.d(TAG, message);
}
/**
* This function return captured image path
*
* @param requestCode on activity result requestCode
* @param resultCode on activity result resultCode
* @param intent on activity result intent
* @return ImageDetails values
*/
public ImageDetails getImagePath(int requestCode, int resultCode, Intent intent) {
ImageDetails imageDetails = new ImageDetails();
if(resultCode == Activity.RESULT_OK) {
if(requestCode == CAMERA_CODE) {
imageDetails.setUri(mImageCaptureUri);
imageDetails.setPath(mImageCaptureUri.getPath());
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), mImageCaptureUri);
} catch (IOException e) {
LogToast(e.getMessage());
e.printStackTrace();
}
imageDetails.setBitmap(bitmap);
imageDetails.setFile(new File(mImageCaptureUri.getPath()));
} else if(requestCode == GALLERY_CODE) {
Uri uri = intent.getData();
imageDetails.setUri(uri);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri);
} catch (IOException e) {
LogToast(e.getMessage());
e.printStackTrace();
}
imageDetails.setBitmap(bitmap);
imageDetails.setFile(new File(uri.getPath()));
imageDetails.setPath(uri.getPath());
} else if(requestCode == CROPPING_CODE) {
try {
if(outPutFile.exists()){
imageDetails.setUri(Uri.fromFile(outPutFile));
imageDetails.setFile(outPutFile);
imageDetails.setPath(outPutFile.getPath());
Bitmap photo = decodeFile(outPutFile);
imageDetails.setBitmap(photo);
}
else {
LogToast("Error while save image");
}
} catch (Exception e) {
e.printStackTrace();
LogToast(e.getMessage());
}
}
} else {
LogToast("user cancelled.");
}
return imageDetails;
}
/**
* Open image pick dialog.<br/>
* CAMERA_CODE</br>
* GALLERY_CODE
*/
public void openImagePickOption() {
final CharSequence[] items = { "Capture Photo", "Choose from Gallery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Capture Photo")) {
captureImage();
} else if (items[item].equals("Choose from Gallery")) {
pickImage();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
/**
* decode from file to bitmap
* @param f file
* @return Bitmap data
*/
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 512;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
Log(e.getMessage());
}
return null;
}
/**
* Capture image using camera <br/>
* REQUEST_CODE = ImagePro.CAMERA_CODE
*/
public void captureImage() {
if(activity != null) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg");
mImageCaptureUri = Uri.fromFile(f);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
activity.startActivityForResult(intent, CAMERA_CODE);
} else {
LogToast("Activity not assigned");
}
}
/**
* pick image from gallery
*/
public void pickImage() {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
activity.startActivityForResult(i, GALLERY_CODE);
}
/**
* cropping the uri image
* @param uri - open cropping dialog using the uri data
*/
public void croppingImage(Uri uri) {
CroppingIMG(uri);
}
int CROP_IMG_X=512;
int CROP_IMG_Y=512;
public void croppingImage(Uri uri, int cropX, int cropY) {
CROP_IMG_X = cropX;
CROP_IMG_Y = cropY;
CroppingIMG(uri);
}
File outPutFile=null;
private void CroppingIMG(Uri uri) {
final ArrayList<CroppingOption> cropOptions = new ArrayList<>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = activity.getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
LogToast("Can't find image croping app");
} else {
intent.setData(uri);
intent.putExtra("outputX", CROP_IMG_X);
intent.putExtra("outputY", CROP_IMG_Y);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
//Create output file here
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outPutFile));
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
activity.startActivityForResult(i, CROPPING_CODE);
} else {
for (ResolveInfo res : list) {
final CroppingOption co = new CroppingOption();
co.title = activity.getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = activity.getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropingOptionAdapter adapter = new CropingOptionAdapter(activity.getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Choose Cropping App");
builder.setCancelable(false);
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
activity.startActivityForResult( cropOptions.get(item).appIntent, CROPPING_CODE);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
@Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
activity.getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
/**
* Capture image using camera<br/>
* REQUEST_CODE = User defined code<br/>
* <br/>
* @param iRequestCode User defined code
*/
public void captureImage(int iRequestCode) {
CAMERA_CODE = iRequestCode;
captureImage();
}
/**
* get path, bitmap, file and uri from image details object
*/
public class ImageDetails {
String path="";
Bitmap bitmap=null;
File file=null;
Uri uri=null;
public Uri getUri() {
return uri;
}
public void setUri(Uri uri) {
this.uri = uri;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
/**
* Created by DP on 7/12/2016.
*/
public class CroppingOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
public class CropingOptionAdapter extends ArrayAdapter {
private ArrayList<CroppingOption> mOptions;
private LayoutInflater mInflater;
public CropingOptionAdapter(Context context, ArrayList<CroppingOption> options) {
super(context, R.layout.croping_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.croping_selector, null);
CroppingOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.img_icon)).setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.txt_name)).setText(item.title);
return convertView;
}
return null;
}
}
}
MainActivity.java
ImagePro imagePro;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagePro = new ImagePro(this);
}
public void onClickUploadImageButton(View view) {
imagePro.openImagePickOption();
}
onActivityResult
if(requestCode == CAMERA_CODE && resultCode == RESULT_OK) {
imageDetails = imagePro.getImagePath(CAMERA_CODE, RESULT_OK, data);
ivCrop.setImageBitmap(imageDetails.getBitmap());
//imageDetails.getPath(), imageDetails.getBitmap(), imageDetails.getUri(), imageDetails.getFile
}
Get and Post methods have nothing to do with the server technology you are using, it works the same in php, asp.net or ruby. GET and POST are part of HTTP protocol. As mark noted, POST is more secure. POST forms are also not cached by the browser. POST is also used to transfer large quantities of data.
If your prefer a GUI interface CurrPorts is free and works with all versions of windows. Shows ports and what process has them open.
You can do that using CSS's background
propieties. There are few ways to do it:
HTML:
<div id="div-with-bg"></div>
CSS:
#div-with-bg
{
background: color url('path') others;
}
HTML:
<div class="div-with-bg"></div>
CSS:
.div-with-bg
{
background: color url('path') others;
}
HTML:
<div style="background: color url('path')"></div>
Where:
background
CSS Property is a connection of all background-xxx propieties in that syntax:
background: background-color background-image background-repeat background-attachment background-position;
Source: w3schools
If I understand your question correctly, it appears you want to know the following:
How do I check if my
String
array containsusercode
, theString
that was just inputted?
See here for a similar question. It quotes solutions that have been pointed out by previous answers. I hope this helps.
I developed a software tool that opens (most) Pickle files directly in your browser (nothing is transferred so it's 100% private):
I find the easiest way is to double up on the quotes to handle a quote.
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)"
Some people like to use CHR(34)*:
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"
*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.
Boolean
types can be null
. You need to do a null
check as you have set it to null
.
if (bool != null && bool)
{
//DoSomething
}
You can just change the reference of input value, as below
<div>
<input type="text" placeholder="Search..." #reference>
<button (click)="reference.value=''">Clear</button>
</div>
David Bradshaw wrote a nice little library that solves this problem. It can be used with or without jQuery.
Available here: https://github.com/davidjbradshaw/imagemap-resizer
In addition to the above, you can do this (where "YourListObjectName" is the name of your table):
Dim LO As ListObject
Set LO = ActiveSheet.ListObjects("YourListObjectName")
But I think that only works if you want to reference a list object that's on the active sheet.
I found your question because I wanted to refer to a list object (a table) on one worksheet that a pivot table on a different worksheet refers to. Since list objects are part of the Worksheets collection, you have to know the name of the worksheet that list object is on in order to refer to it. So to get the name of the worksheet that the list object is on, I got the name of the pivot table's source list object (again, a table) and looped through the worksheets and their list objects until I found the worksheet that contained the list object I was looking for.
Public Sub GetListObjectWorksheet()
' Get the name of the worksheet that contains the data
' that is the pivot table's source data.
Dim WB As Workbook
Set WB = ActiveWorkbook
' Create a PivotTable object and set it to be
' the pivot table in the active cell:
Dim PT As PivotTable
Set PT = ActiveCell.PivotTable
Dim LO As ListObject
Dim LOWS As Worksheet
' Loop through the worksheets and each worksheet's list objects
' to find the name of the worksheet that contains the list object
' that the pivot table uses as its source data:
Dim WS As Worksheet
For Each WS In WB.Worksheets
' Loop through the ListObjects in each workshet:
For Each LO In WS.ListObjects
' If the ListObject's name is the name of the pivot table's soure data,
' set the LOWS to be the worksheet that contains the list object:
If LO.Name = PT.SourceData Then
Set LOWS = WB.Worksheets(LO.Parent.Name)
End If
Next LO
Next WS
Debug.Print LOWS.Name
End Sub
Maybe someone knows a more direct way.
Code check:
This is offtopic here but the people over at CodeReview are more than happy to help you.
I strongly suggest you to do so, there are several things that need attention in your code. Likewise I suggest that you do start reading tutorials since there is really no good reason not to do so.
Lists:
As you said yourself: you need a list of items. The way it is now you only store a reference to one item. Lucky there is exactly that to hold a group of related objects: a List
.
Lists are very straightforward to use but take a look at the related documentation anyway.
A very simple example to keep multiple bikes in a list:
List<Motorbike> bikes = new List<Motorbike>();
bikes.add(new Bike { make = "Honda", color = "brown" });
bikes.add(new Bike { make = "Vroom", color = "red" });
And to iterate over the list you can use the foreach
statement:
foreach(var bike in bikes) {
Console.WriteLine(bike.make);
}
useEffect are isolated within its own scope and gets rendered accordingly. Image from https://reactjs.org/docs/hooks-custom.html
I prefer to use ToString()
and IFormatProvider
.
double value = 100000.3
Console.WriteLine(value.ToString("0,0.00", new CultureInfo("en-US", false)));
Output: 10,000.30
The bytes int can hold depends on what you compiled it for, so when you compile your program for 32 bit processors, it holds numbers from 2^32/2 to -2^32/2+1, while compiled for 64 bit it can hold from 2^64/2 to -2^64/2+1. int32 will always hold 2^32 values.
Edit : Ignore my answer, I didn't see C#. My answer was intended for C and C++. I've never used C#
I got the same trouble, in mobile device with Microsoft's Edge browser. I can solve the problem with: aria-haspopup="true"
. It need to add to the div and the :hover
, :active
, :focus
for the other mobile browsers.
Example html:
<div class="left_bar" aria-haspopup="true">
CSS:
.left_bar:hover, .left_bar:focus, .left_bar:active{
left: 0%;
}
Here's an alternative way to reduce a phone number to valid components using a Scanner
…
let number = "+123 456-7890"
let scanner = Scanner(string: number)
let validCharacters = CharacterSet.decimalDigits
let startCharacters = validCharacters.union(CharacterSet(charactersIn: "+#"))
var digits: NSString?
var validNumber = ""
while !scanner.isAtEnd {
if scanner.scanLocation == 0 {
scanner.scanCharacters(from: startCharacters, into: &digits)
} else {
scanner.scanCharacters(from: validCharacters, into: &digits)
}
scanner.scanUpToCharacters(from: validCharacters, into: nil)
if let digits = digits as? String {
validNumber.append(digits)
}
}
print(validNumber)
// +1234567890
I was just stuck on the same issue, when I've realized that I was using the open short tag form:
<? echo 'nothing will be print if no open_short_tag option is enabled'; ?>
You have to go to your /etc/apache2/php.ini
file and set the short_open_tag = Off
to On
, then sudo service apache2 restart
!
Cheers!
If You have no access to plugin for instance outside of controller You can get params from servicelocator like this
//from POST
$foo = $this->serviceLocator->get('request')->getPost('foo');
//from GET
$foo = $this->serviceLocator->get('request')->getQuery()->foo;
//from route
$foo = $this->serviceLocator->get('application')->getMvcEvent()->getRouteMatch()->getParam('foo');
Whatever you want to use from another module, just put it in the export array. Like this-
@NgModule({
declarations: [TaskCardComponent],
exports: [TaskCardComponent],
imports: [MdCardModule]
})
Try Server.UrlEncode()
, or System.Web.HttpUtility.UrlEncode()
for instances when you don't have access to the Server
object. You can also use System.Uri.EscapeUriString()
to avoid adding a reference to the System.Web
assembly.
The problem for me was the "Browser Link" feature that is very heavy when you have several tabs open for the same project !
Because every time we launched the project, it opens a new tab with browser link communications.
Just close all tabs associated with the project and keep only one open !
This free instantaneously visual studio ! It’s magic ! ;-)
“Browser Link is a feature since Visual Studio 2013 that creates a communication channel between the development environment and one or more web browsers. You can use Browser Link to refresh your web application in several browsers at once, which is useful for cross-browser testing.”
if you are using XDocument.Load(url);
to fetch xml from another domain, it's possible that the host will reject the request and return and unexpected (non-xml) result, which results in the above XmlException
See my solution to this eventuality here: XDocument.Load(feedUrl) returns "Data at the root level is invalid. Line 1, position 1."
The one liner "no imports" version
a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = [1,5,7]
[ a[i] for i in ind_pos ]
for a single line implementation, you can use a lambda expression in a map
map(lambda x:MyModel.objects.get_or_create(name=x), items)
Here, lambda matches each item in items list to x and create a Database record if necessary.
for (Map.Entry<String, String> item : hashMap.entrySet()) {
String key = item.getKey();
String value = item.getValue();
}
res.json
forces the argument to JSON. res.send
will take an non-json object or non-json array and send another type. For example:
This will return a JSON number.
res.json(100)
This will return a status code and issue a warning to use sendStatus.
res.send(100)
If your argument is not a JSON object or array (null,undefined,boolean,string), and you want to ensure it is sent as JSON, use res.json
.
I had mostly the same problem and ended up a a different solution that makes this type of problem trivial to query.
I have a table of sensor data (1 minute data from about 30 sensors)
SensorReadings->(timestamp,value,idSensor)
and I have a sensor table that has lots of mostly static stuff about the sensor but the relevant fields are these:
Sensors->(idSensor,Description,tvLastUpdate,tvLastValue,...)
The tvLastupdate and tvLastValue are set in a trigger on inserts to the SensorReadings table. I always have direct access to these values without needing to do any expensive queries. This does denormalize slightly. The query is trivial:
SELECT idSensor,Description,tvLastUpdate,tvLastValue
FROM Sensors
I use this method for data that is queried often. In my case I have a sensor table, and a large event table, that have data coming in at the minute level AND dozens of machines are updating dashboards and graphs with that data. With my data scenario the trigger-and-cache method works well.
I have found it satisfactory to use ls and cd within ipython notebook to find the file. Then type cat your_file_name into the cell, and you'll get back the contents of the file, which you can then paste into the cell as code.
To insert a sleep command you can use Thread.sleep(2000). So the code would be:
List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
Iterator<Integer> myListIterator = someList.iterator();
while (myListIterator.hasNext()) {
Integer coord = myListIterator.next();
System.out.println(coord);
Thread.Sleep(2000);
}
This would output: 10 20 30 40 50
If you want the numbers after each other you could use: System.out.print(coord +" " ); and if you want to repeat the section you can put it in another while loop.
List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
while(true)
Iterator<Integer> myListIterator = someList.iterator();
while (myListIterator.hasNext()) {
Integer coord = myListIterator.next();
System.out.print(coord + " ");
Thread.Sleep(2000);
}
}
This would output: 10 20 30 40 50 10 20 30 40 50 ... and never stop until you kill the program.
Edit: You do have to put the sleep command in a try catch block
if you want all editing of in a UIViewController you can use.
[[self view]endEditing:YES];
and if you want dismiss a perticular UITextField keyboard hide then use.
1.add delegate in your viewcontroller.h
<UITextFieldDelegate>
make delegation unable to your textfield .
self.yourTextField.delegate = self;
add this method in to your viewcontroller.
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{ [textField resignFirstResponder]; return YES;}
var maxHeight = Math.max.apply(null, $("div.panel").map(function ()
{
return $(this).height();
}).get());
If that's confusing to read, this might be clearer:
var heights = $("div.panel").map(function ()
{
return $(this).height();
}).get();
maxHeight = Math.max.apply(null, heights);
Rationale for the /
POSIX PATH rule
The rule was mentioned at: Why do you need ./ (dot-slash) before executable or script name to run it in bash? but I would like to explain why I think that is a good design in more detail.
First, an explicit full version of the rule is:
/
(e.g. ./someprog
, /bin/someprog
, ./bin/someprog
): CWD is used and PATH isn't/
(e.g. someprog
): PATH is used and CWD isn'tNow, suppose that running:
someprog
would search:
Then, if you wanted to run /bin/someprog
from your distro, and you did:
someprog
it would sometimes work, but others it would fail, because you might be in a directory that contains another unrelated someprog
program.
Therefore, you would soon learn that this is not reliable, and you would end up always using absolute paths when you want to use PATH, therefore defeating the purpose of PATH.
This is also why having relative paths in your PATH is a really bad idea. I'm looking at you, node_modules/bin
.
Conversely, suppose that running:
./someprog
Would search:
Then, if you just downloaded a script someprog
from a git repository and wanted to run it from CWD, you would never be sure that this is the actual program that would run, because maybe your distro has a:
/bin/someprog
which is in you PATH from some package you installed after drinking too much after Christmas last year.
Therefore, once again, you would be forced to always run local scripts relative to CWD with full paths to know what you are running:
"$(pwd)/someprog"
which would be extremely annoying as well.
Another rule that you might be tempted to come up with would be:
relative paths use only PATH, absolute paths only CWD
but once again this forces users to always use absolute paths for non-PATH scripts with "$(pwd)/someprog"
.
The /
path search rule offers a simple to remember solution to the about problem:
PATH
PATH
which makes it super easy to always know what you are running, by relying on the fact that files in the current directory can be expressed either as ./somefile
or somefile
, and so it gives special meaning to one of them.
Sometimes, is slightly annoying that you cannot search for some/prog
relative to PATH
, but I don't see a saner solution to this.
firebaser here
Check the reference documentation for FirebaseInstanceIdService
:
This class was deprecated.
In favour of overriding
onNewToken
inFirebaseMessagingService
. Once that has been implemented, this service can be safely removed.
Weirdly enough the JavaDoc for FirebaseMessagingService
doesn't mention the onNewToken
method yet. It looks like not all updated documentation has been published yet. I've filed an internal issue to get the updates to the reference docs published, and to get the samples in the guide updated too.
In the meantime both the old/deprecated calls, and the new ones should work. If you're having trouble with either, post the code and I'll have a look.
I fixed it by modify my POM file. Notice the last comment under the highest voted answer.
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
The source must matches the target.
@Grantland This "pretty clean solution" looks similar to my own improvement over iPhoneDeveloperTips solution.
You can see my step here: https://gist.github.com/1409855/
/* Original source code courtesy John from iOSDeveloperTips.com */
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
+ (NSString *)getMacAddress
{
int mgmtInfoBase[6];
char *msgBuffer = NULL;
NSString *errorFlag = NULL;
size_t length;
// Setup the management Information Base (mib)
mgmtInfoBase[0] = CTL_NET; // Request network subsystem
mgmtInfoBase[1] = AF_ROUTE; // Routing table info
mgmtInfoBase[2] = 0;
mgmtInfoBase[3] = AF_LINK; // Request link layer information
mgmtInfoBase[4] = NET_RT_IFLIST; // Request all configured interfaces
// With all configured interfaces requested, get handle index
if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
errorFlag = @"if_nametoindex failure";
// Get the size of the data available (store in len)
else if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
errorFlag = @"sysctl mgmtInfoBase failure";
// Alloc memory based on above call
else if ((msgBuffer = malloc(length)) == NULL)
errorFlag = @"buffer allocation failure";
// Get system information, store in buffer
else if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
{
free(msgBuffer);
errorFlag = @"sysctl msgBuffer failure";
}
else
{
// Map msgbuffer to interface message structure
struct if_msghdr *interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
// Map to link-level socket structure
struct sockaddr_dl *socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
// Copy link layer address data in socket structure to an array
unsigned char macAddress[6];
memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);
// Read from char array into a string object, into traditional Mac address format
NSString *macAddressString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
macAddress[0], macAddress[1], macAddress[2], macAddress[3], macAddress[4], macAddress[5]];
NSLog(@"Mac Address: %@", macAddressString);
// Release the buffer memory
free(msgBuffer);
return macAddressString;
}
// Error...
NSLog(@"Error: %@", errorFlag);
return nil;
}
You can do something like this, without using any external libraries.
const fs = require("fs");
const https = require("https");
const file = fs.createWriteStream("data.txt");
https.get("https://www.w3.org/TR/PNG/iso_8859-1.txt", response => {
var stream = response.pipe(file);
stream.on("finish", function() {
console.log("done");
});
});
I've been working on something similar and after a few tries and fails came up with this:
Example: STRING-TO-TEST-ON = 'ab,cd,ef,gh'
I wanted to extract everything after the last occurrence of "," (comma) from the string... resulting in "gh".
My query is:
SELECT SUBSTR('ab,cd,ef,gh' FROM (LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1)) AS `wantedString`
Now let me try and explain what I did ...
I had to find the position of the last "," from the string and to calculate the wantedString length, using LOCATE(",",REVERSE('ab,cd,ef,gh'))-1
by reversing the initial string I actually had to find the first occurrence of the "," in the string ... which wasn't hard to do ... and then -1 to actually find the string length without the ",".
calculate the position of my wantedString by subtracting the string length I've calculated at 1st step from the initial string length:
LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1
I have (+1) because I actually need the string position after the last "," .. and not containing the ",". Hope it makes sense.
I haven't tested the query on large strings so I do not know how slow it is. So if someone actually tests it on a large string I would very happy to know the results.
Not sure how useful this is, but I ended up here from looking for a solution on Netezza SQL and couldn't find one on stack overflow.
For IBM netezza you would use something (for week start mon, week end sun) like:
select next_day (WeddingDate, 'SUN') -6 as WeekStart,
next_day (WeddingDate, 'SUN') as WeekEnd
I know it's a several years old post and you may solve your problem with above solution. However, i just want to suggest using InverseProperty for someone who still need. At least you don't need to change anything in OnModelCreating.
The below code is un-tested.
public class Team
{
[Key]
public int TeamId { get; set;}
public string Name { get; set; }
[InverseProperty("HomeTeam")]
public virtual ICollection<Match> HomeMatches { get; set; }
[InverseProperty("GuestTeam")]
public virtual ICollection<Match> GuestMatches { get; set; }
}
public class Match
{
[Key]
public int MatchId { get; set; }
public float HomePoints { get; set; }
public float GuestPoints { get; set; }
public DateTime Date { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team GuestTeam { get; set; }
}
You can read more about InverseProperty on MSDN: https://msdn.microsoft.com/en-us/data/jj591583?f=255&MSPPError=-2147217396#Relationships
Query to show a 3-variable boolean expression truth table :
;WITH cteData AS
(SELECT 0 AS A, 0 AS B, 0 AS C
UNION ALL SELECT 0,0,1
UNION ALL SELECT 0,1,0
UNION ALL SELECT 0,1,1
UNION ALL SELECT 1,0,0
UNION ALL SELECT 1,0,1
UNION ALL SELECT 1,1,0
UNION ALL SELECT 1,1,1
)
SELECT cteData.*,
CASE WHEN
(A=1) OR (B=1) AND (C=1)
THEN 'True' ELSE 'False' END AS Result
FROM cteData
Results for (A=1) OR (B=1) AND (C=1)
:
A B C Result
0 0 0 False
0 0 1 False
0 1 0 False
0 1 1 True
1 0 0 True
1 0 1 True
1 1 0 True
1 1 1 True
Results for (A=1) OR ( (B=1) AND (C=1) )
are the same.
Results for ( (A=1) OR (B=1) ) AND (C=1)
:
A B C Result
0 0 0 False
0 0 1 False
0 1 0 False
0 1 1 True
1 0 0 False
1 0 1 True
1 1 0 False
1 1 1 True
Hibernate creators discourage doing so in a production environment in their book "Java Persistence with Hibernate":
WARNING: We've seen Hibernate users trying to use SchemaUpdate to update the schema of a production database automatically. This can quickly end in disaster and won't be allowed by your DBA.
My jQuery ajax settings:
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: url,
dataType: "json",
type: "post",
data: params,
success: function (resp){
....
},
error: responseFunc
});
And now i am able to get the request via $request->all()
in Laravel
dataType: "json"
is the important part in the ajax request to handle the response as an json object and not string.
in OpenCV 3.0 you can use it easily as follow:
#combine 2 images same as to concatenate images with two different sizes
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
#create empty martrix (Mat)
res = np.zeros(shape=(max(h1, h2), w1 + w2, 3), dtype=np.uint8)
# assign BGR values to concatenate images
for i in range(res.shape[2]):
# assign img1 colors
res[:h1, :w1, i] = np.ones([img1.shape[0], img1.shape[1]]) * img1[:, :, i]
# assign img2 colors
res[:h2, w1:w1 + w2, i] = np.ones([img2.shape[0], img2.shape[1]]) * img2[:, :, i]
output_img = res.astype('uint8')
While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding
(or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:
sys.stdout.buffer.write(some_bytes_object)
This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.
You have to use Popen like this:
cmd = ['sudo', 'apache2ctl', 'restart']
proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
It expects a list.
If you want only the line number do this:
grep -n Pattern file.ext | gawk '{print $1}' FS=":"
Example:
$ grep -n 9780545460262 EXT20130410.txt | gawk '{print $1}' FS=":"
48793
52285
54023
Method 1:
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "id");
Method 2: You will have to create a class matching your datatable column names and then you can use the following extension method to convert Datatable to List
public static List<T> ToList<T>(this DataTable table) where T : new()
{
List<PropertyInfo> properties = typeof(T).GetProperties().ToList();
List<T> result = new List<T>();
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties);
result.Add(item);
}
return result;
}
private static T CreateItemFromRow<T>(DataRow row, List<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var property in properties)
{
if (row.Table.Columns.Contains(property.Name))
{
if (row[property.Name] != DBNull.Value)
property.SetValue(item, row[property.Name], null);
}
}
return item;
}
and then you can get distinct from list using
YourList.Select(x => x.Id).Distinct();
Please note that this will return you complete Records and not just ids.
(5.65235534).round(2)
#=> 5.65
I propose an alternative method using seaborn
Working code:
import pandas as pd
import seaborn as sns
data=np.random.rand(10,2)*100
df = pd.DataFrame(data, columns=['A', 'B'])
ax= sns.lineplot(data=df, markers= True)
ax.set(xlabel='xlabel', ylabel='ylabel', title='title')
#changing ylables ticks
y_value=['{:,.2f}'.format(x) + '%' for x in ax.get_yticks()]
ax.set_yticklabels(y_value)
You can use jQuery's .eq()
method to get the element with a certain index.
$('ul li').eq(index).css({'background-color':'#343434'});
Yes you can compare with the help of data like below code
UITableViewCell *cell = (UITableViewCell*)[self.view viewWithTag:indexPath.row + 100];
UIImage *secondImage = [UIImage imageNamed:@"boxhover.png"];
NSData *imgData1 = UIImagePNGRepresentation(cell.imageView.image);
NSData *imgData2 = UIImagePNGRepresentation(secondImage);
BOOL isCompare = [imgData1 isEqual:imgData2];
if(isCompare)
{
//contain same image
cell.imageView.image = [UIImage imageNamed:@"box.png"];
}
else
{
//does not contain same image
cell.imageView.image = secondImage;
}
Good contributions the previous ones.
import sys; print(sys.version)
def ingreso(nombre):
print('Hi ', nombre, type(nombre))
def bienvenida(nombre):
print("Hi "+nombre+", bye ")
nombre = raw_input("Enter your name: ")
ingreso(nombre)
bienvenida(nombre)
#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Your name: "))
Enter your name: Joe ('Hi ', 'Joe', <type 'str'>) Hi Joe, bye Your name: Joe Joe
Thanks!
USING DYNAMIC PROGRAMMING IS EFFICIENT
if you want to use it to calculate again and again (like caching)
Java code:
int fact[]=new int[n+1]; //n is the required number you want to find factorial for.
int factorial(int num)
{
if(num==0){
fact[num]=1;
return fact[num];
}
else
fact[num]=(num)*factorial(num-1);
return fact[num];
}
You can follow this Google JavaScript Style Guide
In general, use functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.
EDIT: See nice collection of JavaScript Style Guides And Beautifiers.
If you need to use the vector over and over again and your current code declares it repeatedly within your loop or on every function call, it is likely that you will run out of memory. I suggest that you declare it outside, pass them as pointers in your functions and use:
my_arr.resize()
This way, you keep using the same memory sequence for your vectors instead of requesting for new sequences every time. Hope this helped. Note: resizing it to different sizes may add random values. Pass an integer such as 0 to initialise them, if required.
call srand(sameSeed)
before calling rand()
. More details here.
ECMAScript 6:
Number.MAX_SAFE_INTEGER = Math.pow(2, 53)-1;
Number.MIN_SAFE_INTEGER = -Number.MAX_SAFE_INTEGER;
Take a look at this article which shows the registry keys you need to look for and provides a .NET library that will do this for you.
First, you should to determine if .NET 3.5 is installed by looking at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install, which is a DWORD value. If that value is present and set to 1, then that version of the Framework is installed.
Look at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP, which is a DWORD value which indicates the Service Pack level (where 0 is no service pack).
To be correct about things, you really need to ensure that .NET Fx 2.0 and .NET Fx 3.0 are installed first and then check to see if .NET 3.5 is installed. If all three are true, then you can check for the service pack level.
How do I print out my $ids and $nIds?
print "$ids\n";
print "$nIds\n";
I tried simply print $ids
, but Perl complains.
Complains about what? Uninitialised value? Perhaps your loop was never entered due to an error opening the file. Be sure to check if open
returned an error, and make sure you are using use strict; use warnings;
.
my ($ids, $nIds)
is a list, right? With two elements?
It's a (very special) function call. $ids,$nIds
is a list with two elements.
using System.Configuration;
/// <summary>
/// For read one setting
/// </summary>
/// <param name="key">Key correspondent a your setting</param>
/// <returns>Return the String contains the value to setting</returns>
public string ReadSetting(string key)
{
var appSettings = ConfigurationManager.AppSettings;
return appSettings[key] ?? string.Empty;
}
/// <summary>
/// Read all settings for output Dictionary<string,string>
/// </summary>
/// <returns>Return the Dictionary<string,string> contains all settings</returns>
public Dictionary<string, string> ReadAllSettings()
{
var result = new Dictionary<string, string>();
foreach (var key in ConfigurationManager.AppSettings.AllKeys)
result.Add(key, ConfigurationManager.AppSettings[key]);
return result;
}
Just use the plain ol' class selector.
$('#my_id .my_class')
It doesn't matter if the element also has other classes. It has the .my_class class, and it's somewhere inside #my_id, so it will match that selector.
According to the jQuery selector performance documentation, it's faster to use the two selectors separately, like this:
$('#my_id').find('.my_class')
Here's the relevant part of the documentation:
ID-Based Selectors
// Fast: $( "#container div.robotarm" ); // Super-fast: $( "#container" ).find( "div.robotarm" );
The
.find()
approach is faster because the first selection is handled without going through the Sizzle selector engine – ID-only selections are handled usingdocument.getElementById()
, which is extremely fast because it is native to the browser.
Selecting by ID or by class alone (among other things) invokes browser-supplied functions like document.getElementById()
which are quite rapid, whereas using a descendent selector invokes the Sizzle engine as mentioned which, although fast, is slower than the suggested alternative.
Tried npm install mongoose --msvs_version=2012, if you have multiple Visual installed, it worked for me
var oldString = "stackoverflow";
var str=oldString.replace(/stackover/g,"NO");
$scope.newString= str;
It works for me. Use an intermediate variable.
The solution for me wasn't any of the above. I had to delete (and not recreate) Global.asax and Global.asax.cs. These files existed in the folder, even though they weren't referenced in the project. Apparently the build still saw them. Since I use OWIN with Startup.cs, the Global.asax file was obsolete and there was no issue with deleting it.