Unlike other languages you may be used to, everything in C++ has to be declared before it can be used. The compiler will read your source file from top to bottom, so when it gets to the call to swapCase
, it doesn't know what it is so you get an error. You can declare your function ahead of main with a line like this:
void swapCase(char *name);
or you can simply move the entirety of that function ahead of main in the file. Don't worry about having the seemingly most important function (main) at the bottom of the file. It is very common in C or C++ to do that.
Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below
intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);
intentClearCookies.setIntent(clearcookies);
intentClearCookies.setTitle(R.string.ClearCookies);
intentClearCookies.setEnabled(true);
launchPrefCat.addPreference(intentClearCookies);
And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.
public class ClearCookies extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
showDialog();
}
/**
* @throws NotFoundException
*/
private void showDialog() throws NotFoundException {
new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.ClearCookies))
.setMessage(
getResources().getString(R.string.ClearCookieQuestion))
.setIcon(
getResources().getDrawable(
android.R.drawable.ic_dialog_alert))
.setPositiveButton(
getResources().getString(R.string.PostiveYesButton),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
})
.setNegativeButton(
getResources().getString(R.string.NegativeNoButton),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
}).show();
}}
As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.
You should probably take a look at the various flavours of getResource in the ClassLoader class: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html.
Try like below with Gson
Library.
Earlier Conversion List format were:
[Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]]
and here the conversion source begins.
//** Note I have created the method toString() in Product class.
//Creating and initializing a java.util.List of Product objects
List<Product> productList = (List<Product>)productRepository.findAll();
//Creating a blank List of Gson library JsonObject
List<JsonObject> entities = new ArrayList<JsonObject>();
//Simply printing productList size
System.out.println("Size of productList is : " + productList.size());
//Creating a Iterator for productList
Iterator<Product> iterator = productList.iterator();
//Run while loop till Product Object exists.
while(iterator.hasNext()){
//Creating a fresh Gson Object
Gson gs = new Gson();
//Converting our Product Object to JsonElement
//Object by passing the Product Object String value (iterator.next())
JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class);
//Creating JsonObject from JsonElement
JsonObject jsonObject = element.getAsJsonObject();
//Collecting the JsonObject to List
entities.add(jsonObject);
}
//Do what you want to do with Array of JsonObject
System.out.println(entities);
Converted Json Result is :
[{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}]
Hope this would help many guys!
It's worth noting that the distinct
keyword in HQL does not map directly to the distinct
keyword in SQL.
If you use the distinct
keyword in HQL, then sometimes Hibernate will use the distinct
SQL keyword, but in some situations it will use a result transformer to produce distinct results. For example when you are using an outer join like this:
select distinct o from Order o left join fetch o.lineItems
It is not possible to filter out duplicates at the SQL level in this case, so Hibernate uses a ResultTransformer
to filter duplicates after the SQL query has been performed.
I would like to propose a version, which seems to be more robust, since I ran into a lot of problems using quantile()
in the breaks option cut()
on my dataset.
I am using the ntile
function of plyr
, but it also works with ecdf
as input.
temp[, `:=`(quartile = .bincode(x = ntile(value, 100), breaks = seq(0,100,25), right = TRUE, include.lowest = TRUE)
decile = .bincode(x = ntile(value, 100), breaks = seq(0,100,10), right = TRUE, include.lowest = TRUE)
)]
temp[, `:=`(quartile = .bincode(x = ecdf(value)(value), breaks = seq(0,1,0.25), right = TRUE, include.lowest = TRUE)
decile = .bincode(x = ecdf(value)(value), breaks = seq(0,1,0.1), right = TRUE, include.lowest = TRUE)
)]
Is that correct?
a nice way from http://try.jquery.com/levels/4/challenges/16 :
adding a + before the string without using parseInt and parseFloat and radix and errors i faced for missing radix parameter
sample
var number= +$('#inputForm').val();
Assuming you want all "overlapping" time periods, i.e. all that have at least one day in common.
Try to envision time periods on a straight time line and move them around before your eyes and you will see the necessary conditions.
SELECT *
FROM tbl
WHERE start_date <= '2012-04-12'::date
AND end_date >= '2012-01-01'::date;
This is sometimes faster for me than OVERLAPS
- which is the other good way to do it (as @Marco already provided).
Note the subtle difference (per documentation):
OVERLAPS
automatically takes the earlier value of the pair as the start. Each time period is considered to represent the half-open intervalstart <= time < end
, unless start and end are equal in which case it represents that single time instant. This means for instance that two time periods with only an endpoint in common do not overlap.
Bold emphasis mine.
For big tables the right index can help performance (a lot).
CREATE INDEX tbl_date_inverse_idx ON tbl(start_date, end_date DESC);
Possibly with another (leading) index column if you have additional selective conditions.
Note the inverse order of the two columns. Detailed explanation:
I know the question is old, but if someone is looking for a great new android color picker that use material design I have forked an great project from github and made a simple-to-use android color picker dialog.
This is the project: Android Color Picker
The aar artifact is available at the jcenter repository. Declare the repository and the
dependency in your build.gradle
.
(root)
repositories {
jcenter()
}
(module)
dependencies {
compile 'com.pes.materialcolorpicker:library:1.0.2'
}
Create a color picker dialog object
final ColorPicker cp = new ColorPicker(MainActivity.this, defaultColorR, defaultColorG, defaultColorB);
defaultColorR, defaultColorG, defaultColorB are 3 integer ( value 0-255) for the initialization of the color picker with your custom color value. If you don't want to start with a color set them to 0 or use only the first argument
Then show the dialog (when & where you want) and save the selected color
/* Show color picker dialog */
cp.show();
/* On Click listener for the dialog, when the user select the color */
Button okColor = (Button)cp.findViewById(R.id.okColorButton);
okColor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/* You can get single channel (value 0-255) */
selectedColorR = cp.getRed();
selectedColorG = cp.getGreen();
selectedColorB = cp.getBlue();
/* Or the android RGB Color (see the android Color class reference) */
selectedColorRGB = cp.getColor();
cp.dismiss();
}
});
That's all :)
Try iterating through each element of the list, then splitting it at the tab character and adding it to a new list.
for i in list:
newList.append(i.split('\t')[0])
It's a linker error. ld
is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.
The error message tells you that none of the object files you're linking against contains a definition for avergecolumns
. The reason for that is that the function you've defined is called averagecolumns
(in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).
For YYYYMMDD try
select convert(varchar,getDate(),112)
I have only tested on SQLServer2008.
site-packages
directory where pip is installing your packages.psycopg2
directory).pip install YOUR-PACKAGE
I found the solution for the above program, which had the goal of signing in to http://rediff.com
public class Handle_popupNAlert
{
public static void main(String[] args ) throws InterruptedException
{
WebDriver driver= new FirefoxDriver();
driver.get("http://www.rediff.com/");
WebElement sign = driver.findElement(By.xpath("//html/body/div[3]/div[3]/span[4]/span/a"));
sign.click();
Set<String> windowId = driver.getWindowHandles(); // get window id of current window
Iterator<String> itererator = windowId.iterator();
String mainWinID = itererator.next();
String newAdwinID = itererator.next();
driver.switchTo().window(newAdwinID);
System.out.println(driver.getTitle());
Thread.sleep(3000);
driver.close();
driver.switchTo().window(mainWinID);
System.out.println(driver.getTitle());
Thread.sleep(2000);
WebElement email_id= driver.findElement(By.xpath("//*[@id='c_uname']"));
email_id.sendKeys("hi");
Thread.sleep(5000);
driver.close();
driver.quit();
}
}
For linux environments, you can use xdg-open
. It is installed by default on most distributions. The benefit over the accepted answer is that it opens the user's preferred browser.
$ xdg-open https://google.com
$ xdg-open steam://run/10
Of course you can wrap this in a system()
call.
You can use CURL for this purpose see the example code:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
You are trying to execute the number in the ENDTIME
as a command. You should also see an error like 1370306857: command not found
. Instead use the arithmetic expansion:
echo "It takes $(($ENDTIME - $STARTTIME)) seconds to complete this task..."
You could also save the commands in a separate script, commands.sh
, and use time command:
time commands.sh
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
Using return;
will work just fine. It will not prevent the full loop from completing. It will only stop executing the current iteration of the forEach
loop.
Try the following little program:
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("b");
stringList.add("c");
stringList.stream().forEach(str -> {
if (str.equals("b")) return; // only skips this iteration.
System.out.println(str);
});
}
Output:
a
c
Notice how the return;
is executed for the b
iteration, but c
prints on the following iteration just fine.
The reason the behavior seems unintuitive at first is because we are used to the return
statement interrupting the execution of the whole method. So in this case, we expect the main
method execution as a whole to be halted.
However, what needs to be understood is that a lambda expression, such as:
str -> {
if (str.equals("b")) return;
System.out.println(str);
}
... really needs to be considered as its own distinct "method", completely separate from the main
method, despite it being conveniently located within it. So really, the return
statement only halts the execution of the lambda expression.
The second thing that needs to be understood is that:
stringList.stream().forEach()
... is really just a normal loop under the covers that executes the lambda expression for every iteration.
With these 2 points in mind, the above code can be rewritten in the following equivalent way (for educational purposes only):
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("b");
stringList.add("c");
for(String s : stringList) {
lambdaExpressionEquivalent(s);
}
}
private static void lambdaExpressionEquivalent(String str) {
if (str.equals("b")) {
return;
}
System.out.println(str);
}
With this "less magic" code equivalent, the scope of the return
statement becomes more apparent.
Why not just use the Count property on the List?
for(int cnt3 = 0; cnt3 < integerList.Count; cnt3++)
If a collection is iterable, then it can be iterated using an iterator (and consequently can be used in a for each loop.) The iterator is the actual object that will iterate through the collection.
Given a function, f
, thread it like this:
import threading
threading.Thread(target=f).start()
To pass arguments to f
threading.Thread(target=f, args=(a,b,c)).start()
Note also, the string has a operator[] which returns a Char, and is an IEnumerable<char>
, so for most purposes, you can use a string as a char[]. Hence:
string alpha = "ABCDEFGHIJKLMNOPQRSTUVQXYZ";
for (int i =0; i < 26; ++i)
{
Console.WriteLine(alpha[i]);
}
foreach(char c in alpha)
{
Console.WriteLine(c);
}
JetBrains offer a reasonable explanation,
"Ad-hoc conversion of data structures to text is largely dependent on the current culture, and may lead to unintended results when the code is executed on a machine whose locale differs from that of the original developer. To prevent ambiguities, ReSharper warns you of any instances in code where such a problem may occur."
but if I am working on a site I know will be in English only, I just ignore the suggestion.
There is a good solution to this issue:
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();
***DTO premierDriverInfoDTO = objectMapper.convertValue(jsonString, ***DTO.class);
Map<String, String> map = objectMapper.convertValue(jsonString, Map.class);
Why did this issue occur? I guess you didn't specify the specific type when converting a string to the object, which is a class with a generic type, such as, User <T>.
Maybe there is another way to solve it, using Gson instead of ObjectMapper. (or see here Deserializing Generic Types with GSON)
Gson gson = new GsonBuilder().create();
Type type = new TypeToken<BaseResponseDTO<List<PaymentSummaryDTO>>>(){}.getType();
BaseResponseDTO<List<PaymentSummaryDTO>> results = gson.fromJson(jsonString, type);
BigDecimal revenue = results.getResult().get(0).getRevenue();
According to Mozilla Dev Network, placeholder
is not a valid attribute on a <select>
input.
Instead, add an option with an empty value
and the selected
attribute, as shown below. The empty value
attribute is mandatory to prevent the default behaviour which is to use the contents of the <option>
as the <option>
's value.
<select>
<option value="" selected>select your beverage</option>
<option value="tea">Tea</option>
<option value="coffee">Coffee</option>
<option value="soda">Soda</option>
</select>
In modern browsers, adding the required
attribute to the <select>
element will not allow the user to submit the form which the element is part of if the selected option has an empty value.
If you want to style the default option inside the list (which appears when clicking the element), there's a limited number of CSS properties that are well-supported. color
and background-color
are the 2 safest bets, other CSS properties are likely to be ignored.
In my option the best way (in HTML5) to mark the default option is using the custom data-*
attributes.1 Here's how to style the default option to be greyed out:
select option[data-default] {_x000D_
color: #888;_x000D_
}
_x000D_
<select>_x000D_
<option value="" selected data-default>select your beverage</option>_x000D_
<option value="tea">Tea</option>_x000D_
<option value="coffee">Coffee</option>_x000D_
<option value="soda">Soda</option>_x000D_
</select>
_x000D_
However, this will only style the item inside the drop-down list, not the value displayed on the input. If you want to style that with CSS, target your <select>
element directly. In that case, you can only change the style of the currently selected element at any time.2
If you wanted to make it slightly harder for the user to select the default item, you could set the display: none;
CSS rule on the <option>
, but remember that this will not prevent users from selecting it (using e.g. arrow keys/typing), this just makes it harder for them to do so.
1 This answer previously advised the use of a default
attribute which is non-standard and has no meaning on its own.
2 It's technically possible to style the select itself based on the selected value using JavaScript, but that's outside the scope of this question. This answer, however, covers this method.
The most upvoted answer is not implementing a real slide in/out (or down/up), as:
translateY(-100%)
and then suddenly disappears, causing another glitch on the elements below it.You can implement a slide in and slide out like so:
my-component.ts
import { animate, style, transition, trigger } from '@angular/animations';
@Component({
...
animations: [
trigger('slideDownUp', [
transition(':enter', [style({ height: 0 }), animate(500)]),
transition(':leave', [animate(500, style({ height: 0 }))]),
]),
],
})
my-component.html
<div @slideDownUp *ngIf="isShowing" class="box">
I am the content of the div!
</div>
my-component.scss
.box {
overflow: hidden;
}
What you are doing right now is you are adding .
on the string and not concatenating. It should be,
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
or simply
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '$email'");
Instead of dropping the backup table, just rename it...
BEGIN TRANSACTION;
CREATE TABLE t1_backup(a,b);
INSERT INTO t1_backup SELECT a,b FROM t1;
DROP TABLE t1;
ALTER TABLE t1_backup RENAME TO t1;
COMMIT;
Also if you want to do something like ClassB.Run("thing");
, make sure the Method Run();
is static
or you could call it like this: thing.Run("thing");
.
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
This will format column A as text, B as General, C as a number.
Sub formatColumns()
Columns(1).NumberFormat = "@"
Columns(2).NumberFormat = "General"
Columns(3).NumberFormat = "0"
End Sub
I want to share my experience with this Exception. My JSF 2.2 application worked fine with WildFly 8.0, but one time, when I started server, i got this "Target Unreacheable" exception. Actually, there was no problem with JSF annotations or tags.
Only thing I had to do was cleaning the project. After this operation, my app is working fine again.
I hope this will help someone!
Try this one if you are working with python 2.7:
from __future__ import print_function
Use:
$filenameFormat = "mybackup.zip" + " " + (Get-Date -Format "yyyy-MM-dd")
Rename-Item -Path "C:\temp\mybackup.zip" -NewName $filenameFormat
With jQuery, I've done it this way:
function checkKey(e){
switch (e.keyCode) {
case 40:
alert('down');
break;
case 38:
alert('up');
break;
case 37:
alert('left');
break;
case 39:
alert('right');
break;
default:
alert('???');
}
}
if ($.browser.mozilla) {
$(document).keypress (checkKey);
} else {
$(document).keydown (checkKey);
}
Also, try these plugins, which looks like they do all that work for you:
http://www.openjs.com/scripts/events/keyboard_shortcuts
http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/
The answer to this question in 2020 is IT DOESN'T WORK AT ALL NOW.
Use a List of custom class instances. The custom class is some sort of Pair or Coordinate or whatever. Then just
List<Coordinate> = new YourFavoriteListImplHere<Coordinate>()
This approach has the advantage that it makes satisfying this requirement "perform simple math (like multiplying the pair together to return a single float, etc)" clean, because your custom class can have methods for whatever maths you need to do...
You can use lookups in Ansible in order to get the contents of a file, e.g.
user_data: "{{ lookup('file', user_data_file) }}"
Caveat: This lookup will work with local files, not remote files.
Here's a complete example from the docs:
- hosts: all
vars:
contents: "{{ lookup('file', '/etc/foo.txt') }}"
tasks:
- debug: msg="the value of foo.txt is {{ contents }}"
Calling savefig before show() worked for me.
fig ,ax = plt.subplots(figsize = (4,4))
sns.barplot(x='sex', y='tip', color='g', ax=ax,data=tips)
sns.barplot(x='sex', y='tip', color='b', ax=ax,data=tips)
ax.legend(['Male','Female'], facecolor='w')
plt.savefig('figure.png')
plt.show()
Replace -ggdb with -g and make sure you aren't stripping the binary with the strip command.
Most answers and explanations are not to explain what is a valid string of endDate
or startDate
.
Danny gave us two useful example.
$('#datepicker').datepicker({
startDate: '-2m',
endDate: '+2d'
});
But why?let's take a look at the source code at bootstrap-datetimepicker.js
.
There are some code begin line 1343 tell us how does it work.
if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) {
var part_re = /([-+]\d+)([dmwy])/,
parts = date.match(/([-+]\d+)([dmwy])/g),
part, dir;
date = new Date();
for (var i = 0; i < parts.length; i++) {
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch (part[2]) {
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);
}
There are four kinds of expressions.
w
means weekm
means monthy
means yeard
means dayLook at the regular expression ^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$
.
You can do more than these -0d
or +1m
.
Try harder like startDate:'+1y,-2m,+0d,-1w'
.And the separator ,
could be one of [\f\n\r\t\v,]
jQuery: you think a lot about 'QUERYing the DOM' for DOM elements and doing something.
AngularJS: THE model is the truth, and you always think from that ANGLE.
For example, when you get data from THE server which you intend to display in some format in the DOM, in jQuery, you need to '1. FIND' where in the DOM you want to place this data, the '2. UPDATE/APPEND' it there by creating a new node or just setting its innerHTML. Then when you want to update this view, you then '3. FIND' the location and '4. UPDATE'. This cycle of find and update all done within the same context of getting and formatting data from server is gone in AngularJS.
With AngularJS you have your model (JavaScript objects you are already used to) and the value of the model tells you about the model (obviously) and about the view, and an operation on the model automatically propagates to the view, so you don't have to think about it. You will find yourself in AngularJS no longer finding things in the DOM.
To put in another way, in jQuery, you need to think about CSS selectors, that is, where is the div
or td
that has a class or attribute, etc., so that I can get their HTML or color or value, but in AngularJS, you will find yourself thinking like this: what model am I dealing with, I will set the model's value to true. You are not bothering yourself of whether the view reflecting this value is a checked box or resides in a td
element (details you would have often needed to think about in jQuery).
And with DOM manipulation in AngularJS, you find yourself adding directives and filters, which you can think of as valid HTML extensions.
One more thing you will experience in AngularJS: in jQuery you call the jQuery functions a lot, in AngularJS, AngularJS will call your functions, so AngularJS will 'tell you how to do things', but the benefits are worth it, so learning AngularJS usually means learning what AngularJS wants or the way AngularJS requires that you present your functions and it will call it accordingly. This is one of the things that makes AngularJS a framework rather than a library.
You can leverage Apache Commons StringUtils.isEmpty(str)
, which checks for empty strings and handles null
gracefully.
Example:
System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true
Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str)
.
Example:
System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true
Problem seems to be associated with the SET statement. I think the expression can't be more than 4,000 bytes in size. There is no need to make any changes to any settings if all you are trying to do is to assign a dynamically generated statement that is more than 4,000 characters. What you need to do is to split your assignment. If your statement is 6,000 characters long, find a logical break point and then concatenate second half to the same variable. For example:
SET @Query = 'SELECT ....' [Up To 4,000 characters, then rest of statement as below]
SET @Query = @Query + [rest of statement]
Now run your query as normal i.e. EXEC ( @Query )
It's not doable with CSS2.1, but it is possible with CSS3 attribute substring-matching selectors (which are supported in IE7+):
div[class^="status-"], div[class*=" status-"]
Notice the space character in the second attribute selector. This picks up div
elements whose class
attribute meets either of these conditions:
[class^="status-"]
— starts with "status-"
[class*=" status-"]
— contains the substring "status-" occurring directly after a space character. Class names are separated by whitespace per the HTML spec, hence the significant space character. This checks any other classes after the first if multiple classes are specified, and adds a bonus of checking the first class in case the attribute value is space-padded (which can happen with some applications that output class
attributes dynamically).
Naturally, this also works in jQuery, as demonstrated here.
The reason you need to combine two attribute selectors as described above is because an attribute selector such as [class*="status-"]
will match the following element, which may be undesirable:
<div id='D' class='foo-class foo-status-bar bar-class'></div>
If you can ensure that such a scenario will never happen, then you are free to use such a selector for the sake of simplicity. However, the combination above is much more robust.
If you have control over the HTML source or the application generating the markup, it may be simpler to just make the status-
prefix its own status
class instead as Gumbo suggests.
Since you are still getting duplicate using only UNION
I would check that:
That they are exact duplicates. I mean, if you make a
SELECT DISTINCT * FROM (<your query>) AS subquery
you do get fewer files?
That you don't have already the duplicates in the first part of the query (maybe generated by the left join). As I understand it UNION
it will not add to the result set rows that are already on it, but it won't remove duplicates already present in the first data set.
I had pretty much the same question. After some research, I think that if you want to play the default system "notification sound", you pretty much have to display a notification and tell it to use the default sound. And there's something to be said for the argument in some of the other answers that if you're playing a notification sound, you should be presenting some notification message as well.
However, a little tweaking of the notification API and you can get close to what you want. You can display a blank notification and then remove it automatically after a few seconds. I think this will work for me; maybe it will work for you.
I've created a set of convenience methods in com.globalmentor.android.app.Notifications.java
which allow you create a notification sound like this:
Notifications.notify(this);
The LED will also flash and, if you have vibrate permission, a vibration will occur. Yes, a notification icon will appear in the notification bar but will disappear after a few seconds.
At this point you may realize that, since the notification will go away anyway, you might as well have a scrolling ticker message in the notification bar; you can do that like this:
Notifications.notify(this, 5000, "This text will go away after five seconds.");
There are many other convenience methods in this class. You can download the whole library from its Subversion repository and build it with Maven. It depends on the globalmentor-core library, which can also be built and installed with Maven.
This is using Gson in Kotlin
val listString = "[uno,dos,tres,cuatro,cinco]"
val gson = Gson()
val lista = gson.fromJson(listString , Array<String>::class.java).toList()
Log.e("GSON", lista[0])
Create
trigger `[dbo].[mytrigger]` on `[dbo].[Patients]` after update , insert as
begin
--Sql logic
print 'Hello world'
end
Assuming you have only one record with null in EndDate column for a given RecordID, something like this should give you desired output :
WITH cte1 AS
(
SELECT recordid, MIN(startdate) as min_start , MAX(enddate) as max_end
FROM tmp
GROUP BY recordid
)
SELECT a.recordid, a.min_start ,
CASE
WHEN b.recordid IS NULL THEN a.max_end
END as max_end
FROM cte1 a
LEFT JOIN tmp b ON (b.recordid = a.recordid AND b.enddate IS NULL)
#!/bin/bash
# GNU bash, version 4.3.46
# Determine if the user executing this script is the root user or not
# Display the UID
echo "Your UID is ${UID}"
if [ "${UID}" -eq 0 ]
then
echo "You are root"
else
echo "You are not root user"
fi
Editor's note: If you don't need double brackets, use single ones for code portability.
I don't think the jar tool supports this natively, but you can just unzip a JAR file with "unzip" and specify the output directory with that with the "-d" option, so something like:
$ unzip -d /home/foo/bar/baz /home/foo/bar/Portal.ear Binaries.war
Roll back the most recent migration:
rake db:rollback
Roll back the n
most recent migrations:
rake db:rollback STEP=n
You can find full instructions on the use of Rails migration tasks for rake on the Rails Guide for running migrations.
Here's some more:
rake db:migrate
- Run all migrations that haven't been run alreadyrake db:migrate VERSION=20080906120000
- Run all necessary migrations (up or down) to get to the given versionrake db:migrate RAILS_ENV=test
- Run migrations in the given environmentrake db:migrate:redo
- Roll back one migration and run it againrake db:migrate:redo STEP=n
- Roll back the last n
migrations and run them againrake db:migrate:up VERSION=20080906120000
- Run the up
method for the given migrationrake db:migrate:down VERSION=20080906120000
- Run the down
method for the given migrationAnd to answer your question about where you get a migration's version number from:
The version is the numerical prefix on the migration's filename. For example, to migrate to version 20080906120000 run
$ rake db:migrate VERSION=20080906120000
(From Running Migrations in the Rails Guides)
big=small=values[0]; //assigns element to be highest or lowest value
Should be AFTER
fill loop
//counts to 20 and prompts user for value and stores it
for ( int i = 0; i < 20; i++ )
{
cout << "Enter value " << i << ": ";
cin >> values[i];
}
big=small=values[0]; //assigns element to be highest or lowest value
since when you declare array - it's unintialized
(store some undefined values) and so, your big
and small
after assigning would store undefined
values too.
And of course, you can use std::min_element
, std::max_element
, or std::minmax_element
from C++11
, instead of writing your loops.
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
you try to cast an Array of Object to cast into Array of Integer. You cant do it. This type of downcast is not permitted.
You can make an array of Integer, and after that copy every value of the first array into second array.
Don't know why anyone else hasn't said this yet;
NORMALISE.
You've got a table that models competitions? Competitions are made up of Competitors? You need a distinct list of Competitors in one or more Competitions......
You should have the following tables.....
CREATE TABLE Competitor (
[CompetitorID] INT IDENTITY(1,1) PRIMARY KEY
, [CompetitorName] NVARCHAR(255)
)
CREATE TABLE Competition (
[CompetitionID] INT IDENTITY(1,1) PRIMARY KEY
, [CompetitionName] NVARCHAR(255)
)
CREATE TABLE CompetitionCompetitors (
[CompetitionID] INT
, [CompetitorID] INT
, [Score] INT
, PRIMARY KEY (
[CompetitionID]
, [CompetitorID]
)
)
With Constraints on CompetitionCompetitors.CompetitionID and CompetitorID pointing at the other tables.
With this kind of table structure -- your keys are all simple INTS -- there doesn't seem to be a good NATURAL KEY that would fit the model so I think a SURROGATE KEY is a good fit here.
So if you had this then to get the the distinct list of competitors in a particular competition you can issue a query like this:
DECLARE @CompetitionName VARCHAR(50) SET @CompetitionName = 'London Marathon'
SELECT
p.[CompetitorName] AS [CompetitorName]
FROM
Competitor AS p
WHERE
EXISTS (
SELECT 1
FROM
CompetitionCompetitor AS cc
JOIN Competition AS c ON c.[ID] = cc.[CompetitionID]
WHERE
cc.[CompetitorID] = p.[CompetitorID]
AND cc.[CompetitionName] = @CompetitionNAme
)
And if you wanted the score for each competition a competitor is in:
SELECT
p.[CompetitorName]
, c.[CompetitionName]
, cc.[Score]
FROM
Competitor AS p
JOIN CompetitionCompetitor AS cc ON cc.[CompetitorID] = p.[CompetitorID]
JOIN Competition AS c ON c.[ID] = cc.[CompetitionID]
And when you have a new competition with new competitors then you simply check which ones already exist in the Competitors table. If they already exist then you don't insert into Competitor for those Competitors and do insert for the new ones.
Then you insert the new Competition in Competition and finally you just make all the links in CompetitionCompetitors.
There exists several tools to export/import from SQL Server to Excel.
Google is your friend :-)
We use DbTransfer (which is one of those which can export a complete Database to an Excel file also) here: http://www.dbtransfer.de/Products/DbTransfer.
We have used the openrowset feature of sql server before, but i was never happy with it, becuase it's not very easy to use and lacks of features and speed...
Note that this answer in its bare form is only appropriate for the other use case listed below rather than the one in the question. While mostly fixed, there have been numerous YAML related security vulnerabilities which were caused by loading user input as YAML.
A trick I use for converting strings to bools is YAML.load
, e.g.:
YAML.load(var) # -> true/false if it's one of the below
YAML bool accepts quite a lot of truthy/falsy strings:
y|Y|yes|Yes|YES|n|N|no|No|NO
|true|True|TRUE|false|False|FALSE
|on|On|ON|off|Off|OFF
Assume that you have a piece of config code like this:
config.etc.something = ENV['ETC_SOMETHING']
And in command line:
$ export ETC_SOMETHING=false
Now since ENV
vars are strings once inside code, config.etc.something
's value would be the string "false"
and it would incorrectly evaluate to true
. But if you do like this:
config.etc.something = YAML.load(ENV['ETC_SOMETHING'])
it would be all okay. This is compatible with loading configs from .yml files as well.
Try using:
body {
background-attachment: fixed;
background-image: url(./Images/bg4.jpg);
}
Images
being folder holding the picture that you want to post.
Works for me:
php_curl.dll
file in the ext
folder.This worked for me.
I would like to share my experience with \n
I came to notice that "\n" works as-
puts "\n\n" // to provide 2 new lines
but not
p "\n\n"
also
puts '\n\n'
Doesn't works.
Hope will work for you!!
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()
the x/yticks has the same properties as matplotlib.text
You can try jQuery treegrid (http://maxazan.github.io/jquery-treegrid/) or jQuery treetable (http://ludo.cubicphuse.nl/jquery-treetable/)
Both are using HTML <table>
tag format and styled the as tree.
The jQuery treetable is using data-tt-id
and data-tt-parent-id
for determining the parent and child of the tree. Usage example:
<table id="tree">
<tr data-tt-id="1">
<td>Parent</td>
</tr>
<tr data-tt-id="2" data-tt-parent-id="1">
<td>Child</td>
</tr>
</table>
$("#tree").treetable({ expandable: true });
Meanwhile, jQuery treegrid is using only class for styling the tree. Usage example:
<table class="tree">
<tr class="treegrid-1">
<td>Root node</td><td>Additional info</td>
</tr>
<tr class="treegrid-2 treegrid-parent-1">
<td>Node 1-1</td><td>Additional info</td>
</tr>
<tr class="treegrid-3 treegrid-parent-1">
<td>Node 1-2</td><td>Additional info</td>
</tr>
<tr class="treegrid-4 treegrid-parent-3">
<td>Node 1-2-1</td><td>Additional info</td>
</tr>
</table>
<script type="text/javascript">
$('.tree').treegrid();
</script>
I would recommend to use date->diff function, as in example below:
$dStart = new DateTime('2012-07-26');
$dEnd = new DateTime('2012-08-26');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->format('%r%a'); // use for point out relation: smaller/greater
My guess is that this could be more elegantly solved in this way:
m <- matrix(1:25, ncol = 5)
m[c(1, 6, 13, 25)] <- NA
df <- data.frame(m)
library(dplyr)
df %>%
filter_all(any_vars(is.na(.)))
#> X1 X2 X3 X4 X5
#> 1 NA NA 11 16 21
#> 2 3 8 NA 18 23
#> 3 5 10 15 20 NA
h5py provides a model of datasets and groups. The former is basically arrays and the latter you can think of as directories. Each is named. You should look at the documentation for the API and examples:
http://docs.h5py.org/en/latest/quick.html
A simple example where you are creating all of the data upfront and just want to save it to an hdf5 file would look something like:
In [1]: import numpy as np
In [2]: import h5py
In [3]: a = np.random.random(size=(100,20))
In [4]: h5f = h5py.File('data.h5', 'w')
In [5]: h5f.create_dataset('dataset_1', data=a)
Out[5]: <HDF5 dataset "dataset_1": shape (100, 20), type "<f8">
In [6]: h5f.close()
You can then load that data back in using: '
In [10]: h5f = h5py.File('data.h5','r')
In [11]: b = h5f['dataset_1'][:]
In [12]: h5f.close()
In [13]: np.allclose(a,b)
Out[13]: True
Definitely check out the docs:
Writing to hdf5 file depends either on h5py or pytables (each has a different python API that sits on top of the hdf5 file specification). You should also take a look at other simple binary formats provided by numpy natively such as np.save
, np.savez
etc:
Connection reset simply means that a TCP RST was received. This happens when your peer receives data that it can't process, and there can be various reasons for that.
The simplest is when you close the socket, and then write more data on the output stream. By closing the socket, you told your peer that you are done talking, and it can forget about your connection. When you send more data on that stream anyway, the peer rejects it with an RST to let you know it isn't listening.
In other cases, an intervening firewall or even the remote host itself might "forget" about your TCP connection. This could happen if you don't send any data for a long time (2 hours is a common time-out), or because the peer was rebooted and lost its information about active connections. Sending data on one of these defunct connections will cause a RST too.
Update in response to additional information:
Take a close look at your handling of the SocketTimeoutException
. This exception is raised if the configured timeout is exceeded while blocked on a socket operation. The state of the socket itself is not changed when this exception is thrown, but if your exception handler closes the socket, and then tries to write to it, you'll be in a connection reset condition. setSoTimeout()
is meant to give you a clean way to break out of a read()
operation that might otherwise block forever, without doing dirty things like closing the socket from another thread.
If you are having any one or more row(s) with less or more number of columns than 2 in the dataset then this error may arise.
I am also new to Pyspark and trying to read CSV file. Following code worked for me:
In this code I am using dataset from kaggle the link is: https://www.kaggle.com/carrie1/ecommerce-data
1. Without mentioning the schema:
from pyspark.sql import SparkSession
scSpark = SparkSession \
.builder \
.appName("Python Spark SQL basic example: Reading CSV file without mentioning schema") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
sdfData = scSpark.read.csv("data.csv", header=True, sep=",")
sdfData.show()
Now check the columns: sdfData.columns
Output will be:
['InvoiceNo', 'StockCode','Description','Quantity', 'InvoiceDate', 'CustomerID', 'Country']
Check the datatype for each column:
sdfData.schema
StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,StringType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,StringType,true),StructField(CustomerID,StringType,true),StructField(Country,StringType,true)))
This will give the data frame with all the columns with datatype as StringType
2. With schema: If you know the schema or want to change the datatype of any column in the above table then use this (let's say I am having following columns and want them in a particular data type for each of them)
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField
from pyspark.sql.types import DoubleType, IntegerType, StringType
schema = StructType([\
StructField("InvoiceNo", IntegerType()),\
StructField("StockCode", StringType()), \
StructField("Description", StringType()),\
StructField("Quantity", IntegerType()),\
StructField("InvoiceDate", StringType()),\
StructField("CustomerID", DoubleType()),\
StructField("Country", StringType())\
])
scSpark = SparkSession \
.builder \
.appName("Python Spark SQL example: Reading CSV file with schema") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
sdfData = scSpark.read.csv("data.csv", header=True, sep=",", schema=schema)
Now check the schema for datatype of each column:
sdfData.schema
StructType(List(StructField(InvoiceNo,IntegerType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(CustomerID,DoubleType,true),StructField(Country,StringType,true)))
Edited: We can use the following line of code as well without mentioning schema explicitly:
sdfData = scSpark.read.csv("data.csv", header=True, inferSchema = True)
sdfData.schema
The output is:
StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,DoubleType,true),StructField(CustomerID,IntegerType,true),StructField(Country,StringType,true)))
The output will look like this:
sdfData.show()
+---------+---------+--------------------+--------+--------------+----------+-------+
|InvoiceNo|StockCode| Description|Quantity| InvoiceDate|CustomerID|Country|
+---------+---------+--------------------+--------+--------------+----------+-------+
| 536365| 85123A|WHITE HANGING HEA...| 6|12/1/2010 8:26| 2.55| 17850|
| 536365| 71053| WHITE METAL LANTERN| 6|12/1/2010 8:26| 3.39| 17850|
| 536365| 84406B|CREAM CUPID HEART...| 8|12/1/2010 8:26| 2.75| 17850|
| 536365| 84029G|KNITTED UNION FLA...| 6|12/1/2010 8:26| 3.39| 17850|
| 536365| 84029E|RED WOOLLY HOTTIE...| 6|12/1/2010 8:26| 3.39| 17850|
| 536365| 22752|SET 7 BABUSHKA NE...| 2|12/1/2010 8:26| 7.65| 17850|
| 536365| 21730|GLASS STAR FROSTE...| 6|12/1/2010 8:26| 4.25| 17850|
| 536366| 22633|HAND WARMER UNION...| 6|12/1/2010 8:28| 1.85| 17850|
| 536366| 22632|HAND WARMER RED P...| 6|12/1/2010 8:28| 1.85| 17850|
| 536367| 84879|ASSORTED COLOUR B...| 32|12/1/2010 8:34| 1.69| 13047|
| 536367| 22745|POPPY'S PLAYHOUSE...| 6|12/1/2010 8:34| 2.1| 13047|
| 536367| 22748|POPPY'S PLAYHOUSE...| 6|12/1/2010 8:34| 2.1| 13047|
| 536367| 22749|FELTCRAFT PRINCES...| 8|12/1/2010 8:34| 3.75| 13047|
| 536367| 22310|IVORY KNITTED MUG...| 6|12/1/2010 8:34| 1.65| 13047|
| 536367| 84969|BOX OF 6 ASSORTED...| 6|12/1/2010 8:34| 4.25| 13047|
| 536367| 22623|BOX OF VINTAGE JI...| 3|12/1/2010 8:34| 4.95| 13047|
| 536367| 22622|BOX OF VINTAGE AL...| 2|12/1/2010 8:34| 9.95| 13047|
| 536367| 21754|HOME BUILDING BLO...| 3|12/1/2010 8:34| 5.95| 13047|
| 536367| 21755|LOVE BUILDING BLO...| 3|12/1/2010 8:34| 5.95| 13047|
| 536367| 21777|RECIPE BOX WITH M...| 4|12/1/2010 8:34| 7.95| 13047|
+---------+---------+--------------------+--------+--------------+----------+-------+
only showing top 20 rows
I was looking for the size in GB, so I just improved the code from Superman above with the following changes:
public double GetTotalHDDSize(string driveName)
{
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.IsReady && drive.Name == driveName)
{
return drive.TotalSize / (1024 * 1024 * 1024);
}
}
return -1;
}
It depends on what you are after in the Dictionary
Models.TestModels obj = new Models.TestModels();
foreach (var keyValuPair in obj.sp)
{
// KeyValuePair<int, dynamic>
}
foreach (var key in obj.sp.Keys)
{
// Int
}
foreach (var value in obj.sp.Values)
{
// dynamic
}
That's because they serve different purposes and they both should be used not just one over the other.
The "alt" is for what you guys already said, so you can see what's the image it's all about if the image can't be displayed (for whatever reason), it also allows visually impaired people to understand what's the image about.
The "title" attribute is the correct one to show the tooltip with a title for the image.
According to the W3C, they are the same. In reality, for cross browser safety, you should use window.location
rather than document.location
.
plt.close()
will close current instance.
plt.close(2)
will close figure 2
plt.close(plot1)
will close figure with instance plot1
plt.close('all')
will close all fiures
Found here.
Remember that plt.show()
is a blocking function, so in the example code you used above, plt.close()
isn't being executed until the window is closed, which makes it redundant.
You can use plt.ion()
at the beginning of your code to make it non-blocking, although this has other implications.
After our discussion in the comments, I've put together a bit of an example just to demonstrate how the plot functionality can be used.
Below I create a plot:
fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
....
par_plot, = plot(x_data,y_data, lw=2, color='red')
In this case, ax
above is a handle to a pair of axes. Whenever I want to do something to these axes, I can change my current set of axes to this particular set by calling axes(ax)
.
par_plot
is a handle to the line2D instance. This is called an artist. If I want to change a property of the line, like change the ydata, I can do so by referring to this handle.
I can also create a slider widget by doing the following:
axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)
The first line creates a new axes for the slider (called axsliderA
), the second line creates a slider instance sA
which is placed in the axes, and the third line specifies a function to call when the slider value changes (update
).
My update function could look something like this:
def update(val):
A = sA.val
B = sB.val
C = sC.val
y_data = A*x_data*x_data + B*x_data + C
par_plot.set_ydata(y_data)
draw()
The par_plot.set_ydata(y_data)
changes the ydata property of the Line2D object with the handle par_plot
.
The draw()
function updates the current set of axes.
Putting it all together:
from pylab import *
import matplotlib.pyplot as plt
import numpy
def update(val):
A = sA.val
B = sB.val
C = sC.val
y_data = A*x_data*x_data + B*x_data + C
par_plot.set_ydata(y_data)
draw()
x_data = numpy.arange(-100,100,0.1);
fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
subplots_adjust(top=0.8)
ax.set_xlim(-100, 100);
ax.set_ylim(-100, 100);
ax.set_xlabel('X')
ax.set_ylabel('Y')
axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)
axsliderB = axes([0.43, 0.85, 0.16, 0.075])
sB = Slider(axsliderB, 'B', -30, 30.0, valinit=2)
sB.on_changed(update)
axsliderC = axes([0.74, 0.85, 0.16, 0.075])
sC = Slider(axsliderC, 'C', -30, 30.0, valinit=1)
sC.on_changed(update)
axes(ax)
A = 1;
B = 2;
C = 1;
y_data = A*x_data*x_data + B*x_data + C;
par_plot, = plot(x_data,y_data, lw=2, color='red')
show()
A note about the above: When I run the application, the code runs sequentially right through (it stores the update
function in memory, I think), until it hits show(), which is blocking. When you make a change to one of the sliders, it runs the update function from memory (I think?).
This is the reason why show() is implemented in the way it is, so that you can change values in the background by using functions to process the data.
public int this[int key]
{
get => GetValue(key);
set => SetValue(key, value);
}
Concurrency => When multiple tasks are performed in overlapping time periods with shared resources (potentially maximizing the resources utilization).
Parallel => when single task is divided into multiple simple independent sub-tasks which can be performed simultaneously.
To acheive dynamic filtering follow the link - https://iamvickyav.medium.com/spring-boot-dynamically-ignore-fields-while-converting-java-object-to-json-e8d642088f55
Add the @JsonFilter("Filter name") annotation to the model class.
Inside the controller function add the code:-
SimpleBeanPropertyFilter simpleBeanPropertyFilter =
SimpleBeanPropertyFilter.serializeAllExcept("id", "dob");
FilterProvider filterProvider = new SimpleFilterProvider()
.addFilter("Filter name", simpleBeanPropertyFilter);
List<User> userList = userService.getAllUsers();
MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(userList);
mappingJacksonValue.setFilters(filterProvider);
return mappingJacksonValue;
make sure the return type is MappingJacksonValue.
Well, I think that there are simple solutions than mentioned here on this page! first of all, let's make an example:
You have 1 DIV and want to hide thas DIV on Desktop and show on Mobile (or vice versa). So, let's presume that the DIV position placed in the Head
section and named as header_div
.
The global code in your CSS file
will be: (for the same DIV):
.header_div {
display: none;
}
@media all and (max-width: 768px){
.header_div {
display: block;
}
}
So simple and no need to make 2 div's one for desktop and the other for mobile.
Hope this helps.
Thank you.
The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:
File > Preferences > Settings > Encoding > Choose your option
This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.
The other answers demonstrate the difference between array_walk (in-place modification) and array_map (return modified copy) quite well. However, they don't really mention array_reduce, which is an illuminating way to understand array_map and array_filter.
The array_reduce function takes an array, a two-argument function and an 'accumulator', like this:
array_reduce(array('a', 'b', 'c', 'd'),
'my_function',
$accumulator)
The array's elements are combined with the accumulator one at a time, using the given function. The result of the above call is the same as doing this:
my_function(
my_function(
my_function(
my_function(
$accumulator,
'a'),
'b'),
'c'),
'd')
If you prefer to think in terms of loops, it's like doing the following (I've actually used this as a fallback when array_reduce wasn't available):
function array_reduce($array, $function, $accumulator) {
foreach ($array as $element) {
$accumulator = $function($accumulator, $element);
}
return $accumulator;
}
This looping version makes it clear why I've called the third argument an 'accumulator': we can use it to accumulate results through each iteration.
So what does this have to do with array_map and array_filter? It turns out that they're both a particular kind of array_reduce. We can implement them like this:
array_map($function, $array) === array_reduce($array, $MAP, array())
array_filter($array, $function) === array_reduce($array, $FILTER, array())
Ignore the fact that array_map and array_filter take their arguments in a different order; that's just another quirk of PHP. The important point is that the right-hand-side is identical except for the functions I've called $MAP and $FILTER. So, what do they look like?
$MAP = function($accumulator, $element) {
$accumulator[] = $function($element);
return $accumulator;
};
$FILTER = function($accumulator, $element) {
if ($function($element)) $accumulator[] = $element;
return $accumulator;
};
As you can see, both functions take in the $accumulator and return it again. There are two differences in these functions:
Note that this is far from useless trivia; we can use it to make our algorithms more efficient!
We can often see code like these two examples:
// Transform the valid inputs
array_map('transform', array_filter($inputs, 'valid'))
// Get all numeric IDs
array_filter(array_map('get_id', $inputs), 'is_numeric')
Using array_map and array_filter instead of loops makes these examples look quite nice. However, it can be very inefficient if $inputs is large, since the first call (map or filter) will traverse $inputs and build an intermediate array. This intermediate array is passed straight into the second call, which will traverse the whole thing again, then the intermediate array will need to be garbage collected.
We can get rid of this intermediate array by exploiting the fact that array_map and array_filter are both examples of array_reduce. By combining them, we only have to traverse $inputs once in each example:
// Transform valid inputs
array_reduce($inputs,
function($accumulator, $element) {
if (valid($element)) $accumulator[] = transform($element);
return $accumulator;
},
array())
// Get all numeric IDs
array_reduce($inputs,
function($accumulator, $element) {
$id = get_id($element);
if (is_numeric($id)) $accumulator[] = $id;
return $accumulator;
},
array())
NOTE: My implementations of array_map and array_filter above won't behave exactly like PHP's, since my array_map can only handle one array at a time and my array_filter won't use "empty" as its default $function. Also, neither will preserve keys.
It's not difficult to make them behave like PHP's, but I felt that these complications would make the core idea harder to spot.
i had this problem, and resolved it editing httd.conf
<IfModule headers_module>
<IfVersion >= 2.4.7 >
Header always setifempty X-Frame-Options GOFORIT
</IfVersion>
<IfVersion < 2.4.7 >
Header always merge X-Frame-Options GOFORIT
</IfVersion>
</IfModule>
i changed SAMEORIGIN to GOFORIT and restarted server
Another way -
Add these lines to your application config file configuration section:
<system.net>
<settings>
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
Here is my step by step experience, inspired by typeahead examples, from a Scala/PlayFramework app we are working on.
In a script LearnerNameTypeAhead.coffee
(convertible of course to JS) I have:
$ ->
learners = new Bloodhound(
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value")
queryTokenizer: Bloodhound.tokenizers.whitespace
remote: "/learner/namelike?nameLikeStr=%QUERY"
)
learners.initialize()
$("#firstName").typeahead
minLength: 3
hint: true
highlight:true
,
name: "learners"
displayKey: "value"
source: learners.ttAdapter()
I included the typeahead bundle and my script on the page, and there is a div
around my input field as follows:
<script [email protected]("javascripts/typeahead.bundle.js")></script>
<script [email protected]("javascripts/LearnerNameTypeAhead.js") type="text/javascript" ></script>
<div>
<input name="firstName" id="firstName" class="typeahead" placeholder="First Name" value="@firstName">
</div>
The result is that for each character typed in the input field after the first minLength (3) characters, the page issues a GET request with a URL looking like /learner/namelike?nameLikeStr=
plus the currently typed characters. The server code returns a json array of objects containing fields "id" and "value", for example like this:
[ {
"id": "109",
"value": "Graham Jones"
},
{
"id": "5833",
"value": "Hezekiah Jones"
} ]
For play I need something in the routes file:
GET /learner/namelike controllers.Learners.namesLike(nameLikeStr:String)
And finally, I set some of the styling for the dropdown, etc. in a new typeahead.css file which I included in the page's <head>
(or accessible .css)
.tt-dropdown-menu {
width: 252px;
margin-top: 12px;
padding: 8px 0;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, 0.2);
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
-webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
-moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
box-shadow: 0 5px 10px rgba(0,0,0,.2);
}
.typeahead {
background-color: #fff;
}
.typeahead:focus {
border: 2px solid #0097cf;
}
.tt-query {
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.tt-hint {
color: #999
}
.tt-suggestion {
padding: 3px 20px;
font-size: 18px;
line-height: 24px;
}
.tt-suggestion.tt-cursor {
color: #fff;
background-color: #0097cf;
}
.tt-suggestion p {
margin: 0;
}
In PHP, use mysqli_real_escape_string.
Example from the PHP Manual:
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");
$city = "'s Hertogenbosch";
/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("Error: %s\n", mysqli_sqlstate($link));
}
$city = mysqli_real_escape_string($link, $city);
/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("%d Row inserted.\n", mysqli_affected_rows($link));
}
mysqli_close($link);
?>
I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.
<ul ng-repeat="vote in votes" ...>
<li data-choice="selected" data-value="vote.id">...</li>
</ul>
import os
import stat
import shutil
def errorRemoveReadonly(func, path, exc):
excvalue = exc[1]
if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
# change the file to be readable,writable,executable: 0777
os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
# retry
func(path)
else:
# raiseenter code here
shutil.rmtree(path, ignore_errors=False, onerror=errorRemoveReadonly)
If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised.enter code here
I got my R code file from a friend and was not able to run read.csv command but If I copy the same command(read.csv ) to a new R script file, it ran fine.
Below command was not running in R code file shared by my friend, working directory,file name etc were all correct because If I created a new R script file and ran below command ,it worked.
df <- read.csv("file.csv",header=TRUE,stringsAsFactors = FALSE,strip.white =
TRUE,sep = ',')
issue/resolution: I right clicked the R code file and unblocked the file and click save button and issue got resolved. I your R code file is in Downloads folder in windows , then move to some other folder.
p = {1,2,3} is wrong.
You can never use this:
int * p;
p = {1,2,3};
loop is right
int *p,i;
p = malloc(3*sizeof(int));
for(i = 0; i<3; ++i)
p[i] = i;
On Windows it ended up being that the port was already in use by IIS.
Stopping IIS (Right-click, Exit), resolved the issue.
int *p=(int *)0x1234 = 10; //0x1234 is the memory address and value 10 is assigned in that address
unsigned int *ptr=(unsigned int *)0x903jf = 20;//0x903j is memory address and value 20 is assigned
Basically in Embedded platform we are using directly addresses instead of names
Just thought I'd add that I've improved Mud's SimplerAES by adding a random IV that's passed back inside the encrypted string. This improves the encryption as encrypting the same string will result in a different output each time.
public class StringEncryption
{
private readonly Random random;
private readonly byte[] key;
private readonly RijndaelManaged rm;
private readonly UTF8Encoding encoder;
public StringEncryption()
{
this.random = new Random();
this.rm = new RijndaelManaged();
this.encoder = new UTF8Encoding();
this.key = Convert.FromBase64String("Your+Secret+Static+Encryption+Key+Goes+Here=");
}
public string Encrypt(string unencrypted)
{
var vector = new byte[16];
this.random.NextBytes(vector);
var cryptogram = vector.Concat(this.Encrypt(this.encoder.GetBytes(unencrypted), vector));
return Convert.ToBase64String(cryptogram.ToArray());
}
public string Decrypt(string encrypted)
{
var cryptogram = Convert.FromBase64String(encrypted);
if (cryptogram.Length < 17)
{
throw new ArgumentException("Not a valid encrypted string", "encrypted");
}
var vector = cryptogram.Take(16).ToArray();
var buffer = cryptogram.Skip(16).ToArray();
return this.encoder.GetString(this.Decrypt(buffer, vector));
}
private byte[] Encrypt(byte[] buffer, byte[] vector)
{
var encryptor = this.rm.CreateEncryptor(this.key, vector);
return this.Transform(buffer, encryptor);
}
private byte[] Decrypt(byte[] buffer, byte[] vector)
{
var decryptor = this.rm.CreateDecryptor(this.key, vector);
return this.Transform(buffer, decryptor);
}
private byte[] Transform(byte[] buffer, ICryptoTransform transform)
{
var stream = new MemoryStream();
using (var cs = new CryptoStream(stream, transform, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
}
return stream.ToArray();
}
}
And bonus unit test
[Test]
public void EncryptDecrypt()
{
// Arrange
var subject = new StringEncryption();
var originalString = "Testing123!£$";
// Act
var encryptedString1 = subject.Encrypt(originalString);
var encryptedString2 = subject.Encrypt(originalString);
var decryptedString1 = subject.Decrypt(encryptedString1);
var decryptedString2 = subject.Decrypt(encryptedString2);
// Assert
Assert.AreEqual(originalString, decryptedString1, "Decrypted string should match original string");
Assert.AreEqual(originalString, decryptedString2, "Decrypted string should match original string");
Assert.AreNotEqual(originalString, encryptedString1, "Encrypted string should not match original string");
Assert.AreNotEqual(encryptedString1, encryptedString2, "String should never be encrypted the same twice");
}
My rule of thumb is:
&
)const
if it's an incoming parameter)const T&
).int ¤t = someArray[i]
)Regardless which one you use, don't forget to document your functions and the meaning of their parameters if they are not obvious.
Note that starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), it's possible to improve a bit on Krzysztof Krason's solution by capturing the match result directly within the if condition as a variable and re-use it in the condition's body:
# pattern = '<title>(.*)</title>'
# text = '<title>hello</title>'
if match := re.search(pattern, text, re.IGNORECASE):
title = match.group(1)
# hello
On SQL Server Management Studio
Done.
There are several NuGet packages for this, but all are currently in pre-release version.
[Update] As of June 2018, Capgemini.Cauldron.Core.JavaProperties is now in a stable version (version 2.1.0 and 3.0.20).
If you run into this problem and are working with a non-Windows/Mac OS (Ubuntu in my case), try starting the emulator by itself in Android SDK and AVD Manager then running your application.
finally...
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[RA2Newsletter]
ON [dbo].[Reiseagent]
AFTER INSERT
AS
declare
@rAgent_Name nvarchar(50),
@rAgent_Email nvarchar(50),
@rAgent_IP nvarchar(50),
@hotelID int,
@retval int
BEGIN
SET NOCOUNT ON;
-- Insert statements for trigger here
Select @rAgent_Name=rAgent_Name,@rAgent_Email=rAgent_Email,@rAgent_IP=rAgent_IP,@hotelID=hotelID From Inserted
EXEC insert2Newsletter '','',@rAgent_Name,@rAgent_Email,@rAgent_IP,@hotelID,'RA', @retval
END
SRC = a.cpp b.cpp
BIN = $(patsubst %.cpp,%,$(SRC))
all: $(BIN)
clean:
rm -f $(BIN)
.PHONY: all clean
make all
will do:
c++ a.cpp -o a
c++ b.cpp -o b
If you set CXX
and CXXFLAGS
variables make
will use them.
Either one would work. It depends on your needs:
If your bean identifier contains special character(s) for example (/viewSummary.html
), it wont be allowed as the bean id
, because it's not a valid XML ID. In such cases you could skip defining the bean id
and supply the bean name
instead.
The name
attribute also helps in defining alias
es for your bean, since it allows specifying multiple identifiers for a given bean.
Use defaultdict instead:
from collections import defaultdict
data = defaultdict(list)
data[1].append('hello')
This way you don't have to initialize all the keys you want to use to lists beforehand.
What is happening in your example is that you use one (mutable) list:
alist = [1]
data = dict.fromkeys(range(2), alist)
alist.append(2)
print data
would output {0: [1, 2], 1: [1, 2]}
.
Thanks for the pointers.
I don't know, whether this is the best approach to the problem or not, but here is how I got it to work. I referenced the Microsoft XML, v2.6 dll in my VBA, and then the following code snippet, gives me the required values
Dim objXML As MSXML2.DOMDocument
Set objXML = New MSXML2.DOMDocument
If Not objXML.loadXML(strXML) Then 'strXML is the string with XML'
Err.Raise objXML.parseError.ErrorCode, , objXML.parseError.reason
End If
Dim point As IXMLDOMNode
Set point = objXML.firstChild
Debug.Print point.selectSingleNode("X").Text
Debug.Print point.selectSingleNode("Y").Text
Use cron with find to delete files older than given threshold. For example to delete files that haven't been accessed for at least a week.
find .session/ -atime +7 -exec rm {} \;
Ok uninstall the app, but we admit that the data not must be lost? This can be resolve, upgrading versionCode and versionName and try the application in "Release" mode.
For example, this is important when we want to try the migration of our Database. We can compare the our application on play store with actual application not release yet.
Why this issue is happening is because Android framework can't guarantee your service get started within 5 second but on the other hand framework does have strict limit on foreground notification must be fired within 5 seconds, without checking if framework had tried to start the service.
This is definitely a framework issue, but not all developers facing this issue are doing their best:
startForeground
a notification must be in both onCreate
and onStartCommand
, because if your service is already created and somehow your activity is trying to start it again, onCreate
won't be called.
notification ID must not be 0 otherwise same crash will happen even it's not same reason.
stopSelf
must not be called before startForeground
.
With all above 3 this issue can be reduced a bit but still not a fix, the real fix or let's say workaround is to downgrade your target sdk version to 25.
And note that most likely Android P will still carry this issue because Google refuses to even understand what is going on and does not believe this is their fault, read #36 and #56 for more information
The line should be:
numpy.concatenate([a,b])
The arrays you want to concatenate need to be passed in as a sequence, not as separate arguments.
From the NumPy documentation:
numpy.concatenate((a1, a2, ...), axis=0)
Join a sequence of arrays together.
It was trying to interpret your b
as the axis parameter, which is why it complained it couldn't convert it into a scalar.
Aside from other great responses, I just had to give NTFS permissions to the Oracle installation folder. (I gave read access)
Here's the most simplest code for everyone
Note: Showing Pearson's Rho and not R^2.
library(ggplot2)
library(ggpubr)
df <- data.frame(x = c(1:100)
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
geom_point()+
stat_cor(label.y = 35)+ #this means at 35th unit in the y axis, the r squared and p value will be shown
stat_regline_equation(label.y = 30) #this means at 30th unit regresion line equation will be shown
p
Name2 is a field. WPF binds only to properties. Change it to:
public string Name2 { get; set; }
Be warned that with this minimal implementation, your TextBox won't respond to programmatic changes to Name2. So for your timer update scenario, you'll need to implement INotifyPropertyChanged:
partial class Window1 : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private string _name2;
public string Name2
{
get { return _name2; }
set
{
if (value != _name2)
{
_name2 = value;
OnPropertyChanged("Name2");
}
}
}
}
You should consider moving this to a separate data object rather than on your Window class.
See the deprecation in the docs
.loc
uses label based indexing to select both rows and columns. The labels being the values of the index or the columns. Slicing with .loc
includes the last element.
Let's assume we have a DataFrame with the following columns:
foo
,bar
,quz
,ant
,cat
,sat
,dat
.
# selects all rows and all columns beginning at 'foo' up to and including 'sat'
df.loc[:, 'foo':'sat']
# foo bar quz ant cat sat
.loc
accepts the same slice notation that Python lists do for both row and columns. Slice notation being start:stop:step
# slice from 'foo' to 'cat' by every 2nd column
df.loc[:, 'foo':'cat':2]
# foo quz cat
# slice from the beginning to 'bar'
df.loc[:, :'bar']
# foo bar
# slice from 'quz' to the end by 3
df.loc[:, 'quz'::3]
# quz sat
# attempt from 'sat' to 'bar'
df.loc[:, 'sat':'bar']
# no columns returned
# slice from 'sat' to 'bar'
df.loc[:, 'sat':'bar':-1]
sat cat ant quz bar
# slice notation is syntatic sugar for the slice function
# slice from 'quz' to the end by 2 with slice function
df.loc[:, slice('quz',None, 2)]
# quz cat dat
# select specific columns with a list
# select columns foo, bar and dat
df.loc[:, ['foo','bar','dat']]
# foo bar dat
You can slice by rows and columns. For instance, if you have 5 rows with labels v
, w
, x
, y
, z
# slice from 'w' to 'y' and 'foo' to 'ant' by 3
df.loc['w':'y', 'foo':'ant':3]
# foo ant
# w
# x
# y
public Dictionary<string, object> ToDictionary<T>(string key, T value)
{
try
{
var payload = new Dictionary<string, object>
{
{ key, value }
};
} catch (Exception e)
{
return null;
}
}
public T FromDictionary<T>(Dictionary<string, object> payload, string key)
{
try
{
JObject jObject = (JObject) payload[key];
T t = jObject.ToObject<T>();
return (t);
}
catch(Exception e) {
return default(T);
}
}
HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.
It's possible to have HTML form elements disabled -- wouldn't that do? Your users would see it in one of three states, i.e. checked, unchecked, and disabled, which would be greyed out and not clickable. To me, that seems similar to "null" or "not applicable" or whatever you're looking for in that third state.
http://www.markrafferty.com/wp-content/w3tc/min/7415c412.e68ae1.css
Line 11:
.postItem img {
height: auto;
width: 450px;
}
You can either edit your CSS, or you can listen to Mageek and use INLINE STYLING to override the CSS styling that's happening:
<img src="theSource" style="width:30px;" />
Avoid setting both width and height, as the image itself might not be scaled proportionally. But you can set the dimensions to whatever you want, as per Mageek's example.
This works for me:
import Cookies from 'universal-cookie';
const cookies = new Cookies();
function headers(set_cookie=false) {
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}
Then build your call:
export function fetchTests(user_id) {
return function (dispatch) {
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
body: JSON.stringify({
user_id: user_id
}),
headers: headers(true)
};
return fetch('/api/v1/tests/listing/', data)
.then(response => response.json())
.then(json => dispatch(receiveTests(json)));
};
}
In C#, you'd do something like this:
MyButton.Attributes.Add("onclick", "put your javascript here including... return false;");
matrix multiplication, see the following example:
> A <- matrix (c(1,3,4, 5,8,9, 1,3,3), 3,3)
> A
[,1] [,2] [,3]
[1,] 1 5 1
[2,] 3 8 3
[3,] 4 9 3
>
> B <- matrix (c(2,4,5, 8,9,2, 3,4,5), 3,3)
>
> B
[,1] [,2] [,3]
[1,] 2 8 3
[2,] 4 9 4
[3,] 5 2 5
>
>
> A %*% B
[,1] [,2] [,3]
[1,] 27 55 28
[2,] 53 102 56
[3,] 59 119 63
> B %*% A
[,1] [,2] [,3]
[1,] 38 101 35
[2,] 47 128 43
[3,] 31 86 26
Also see:
http://en.wikipedia.org/wiki/Matrix_multiplication
If this does not follow the size of matrix rule you will get the error:
> A <- matrix(c(1,2,3,4,5,6), 3,2)
> A
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> B <- matrix (c(3,1,3,4,4,4,4,4,3), 3,3)
> B
[,1] [,2] [,3]
[1,] 3 4 4
[2,] 1 4 4
[3,] 3 4 3
> A%*%B
Error in A %*% B : non-conformable arguments
ASPX file:
<h2><p>Notify:</p> <asp:Literal runat="server" ID="ltNotify" /></h2>
ASPX.CS file:
ltNotify.Text = "Alert!";
It generally comes to mind that you have set up two-factor authentication, after a few password trials and maybe a password reset. So, how can we git clone a private repository using two-factor authentication? It is simple, using access tokens.
How to Authenticate Git using Access Tokens
Wow, it works!
Dim tblReady1 As DataTable = tblReady.Clone()
'' convert all the columns type to String
For Each col As DataColumn In tblReady1.Columns
col.DataType = GetType(String)
Next
tblReady1.Load(tblReady.CreateDataReader)
Here's a pure JavaScript function which will simulate a click (or any mouse event) on a target element:
function simulatedClick(target, options) {
var event = target.ownerDocument.createEvent('MouseEvents'),
options = options || {},
opts = { // These are the default values, set up for un-modified left clicks
type: 'click',
canBubble: true,
cancelable: true,
view: target.ownerDocument.defaultView,
detail: 1,
screenX: 0, //The coordinates within the entire page
screenY: 0,
clientX: 0, //The coordinates within the viewport
clientY: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false, //I *think* 'meta' is 'Cmd/Apple' on Mac, and 'Windows key' on Win. Not sure, though!
button: 0, //0 = left, 1 = middle, 2 = right
relatedTarget: null,
};
//Merge the options with the defaults
for (var key in options) {
if (options.hasOwnProperty(key)) {
opts[key] = options[key];
}
}
//Pass in the options
event.initMouseEvent(
opts.type,
opts.canBubble,
opts.cancelable,
opts.view,
opts.detail,
opts.screenX,
opts.screenY,
opts.clientX,
opts.clientY,
opts.ctrlKey,
opts.altKey,
opts.shiftKey,
opts.metaKey,
opts.button,
opts.relatedTarget
);
//Fire the event
target.dispatchEvent(event);
}
Here's a working example: http://www.spookandpuff.com/examples/clickSimulation.html
You can simulate a click on any element in the DOM. Something like simulatedClick(document.getElementById('yourButtonId'))
would work.
You can pass in an object into options
to override the defaults (to simulate which mouse button you want, whether Shift/Alt/Ctrl are held, etc. The options it accepts are based on the MouseEvents API.
I've tested in Firefox, Safari and Chrome. Internet Explorer might need special treatment, I'm not sure.
Try this..
List<Cat> cats = new List<Cat>
{
new Cat(){ Name = "Sylvester", Age=8 },
new Cat(){ Name = "Whiskers", Age=2 },
new Cat(){ Name = "Sasha", Age=14 }
};
Session["data"] = cats;
foreach (Cat c in cats)
System.Diagnostics.Debug.WriteLine("Cats>>" + c.Name); //DEBUGGG
<div className={['foo', condition && 'bar'].filter(Boolean).join(' ')} />
.filter(Boolean)
removes "falsey" values from the array. Since class names must be strings, anything other than that would not be included in the new filtered array.
console.log( ['foo', true && 'bar'].filter(Boolean).join(' ') )
console.log( ['foo', false && 'bar'].filter(Boolean).join(' ') )
_x000D_
const cx = (...list) => list.filter(Boolean).join(' ')
// usage:
<div className={cx('foo', condition && 'bar')} />
var cx = (...list) => list.filter(Boolean).join(' ')
console.log( cx('foo', 1 && 'bar', 1 && 'baz') )
console.log( cx('foo', 0 && 'bar', 1 && 'baz') )
console.log( cx('foo', 0 && 'bar', 0 && 'baz') )
_x000D_
There is really no advantage in using Object.create(...)
over new object
.
Those advocating this method generally state rather ambiguous advantages: "scalability", or "more natural to JavaScript" etc.
However, I have yet to see a concrete example that shows that Object.create
has any advantages over using new
. On the contrary there are known problems with it. Sam Elsamman describes what happens when there are nested objects and Object.create(...)
is used:
var Animal = {
traits: {},
}
var lion = Object.create(Animal);
lion.traits.legs = 4;
var bird = Object.create(Animal);
bird.traits.legs = 2;
alert(lion.traits.legs) // shows 2!!!
This occurs because Object.create(...)
advocates a practice where data is used to create new objects; here the Animal
datum becomes part of the prototype of lion
and bird
, and causes problems as it is shared. When using new the prototypal inheritance is explicit:
function Animal() {
this.traits = {};
}
function Lion() { }
Lion.prototype = new Animal();
function Bird() { }
Bird.prototype = new Animal();
var lion = new Lion();
lion.traits.legs = 4;
var bird = new Bird();
bird.traits.legs = 2;
alert(lion.traits.legs) // now shows 4
Regarding, the optional property attributes that are passed into Object.create(...)
, these can be added using Object.defineProperties(...)
.
It's pretty simple. Pay attention and you'll get it right away! :)
You will create a html array, which will be then sent to php array. Your html code will look like this:
<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">
Where [1] [2] [3]
are the ID
s of your messages, meaning that you will echo
your $row['Report ID']
in their place.
Then, when you submit the form, your PHP array will look like this:
print_r($check_list)
[1] => checked
[3] => checked
Depending on which were checked and which were not.
I'm sure you can continue from this point forward.
Using Apache Commons IO.
import org.apache.commons.io.FileUtils;
//...
String contents = FileUtils.readFileToString(new File("/path/to/the/file"), "UTF-8")
You can see de javadoc for the method for details.
You can do so by creating an array of dtype=object
. If you try to assign a long string to a normal numpy array, it truncates the string:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'],
dtype='|S6')
But when you use dtype=object
, you get an array of python object references. So you can have all the behaviors of python strings:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)
Indeed, because it's an array of objects, you can assign any kind of python object to the array:
>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)
However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:
>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop
datetime.datetime.now
is not timezone aware.
Django comes with a helper for this, which requires pytz
from django.utils import timezone
now = timezone.now()
You should be able to compare now
to challenge.datetime_start
You can use jQuery to do that for you.
$(document).ready(function() {
// put Ajax here.
});
Check it here:
http://docs.jquery.com/Tutorials:Introducing_%24%28document%29.ready%28%29
Easy with a directive
Html:
<input type="file" file-upload multiple/>
JS:
app.directive('fileUpload', function () {
return {
scope: true, //create a new scope
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var files = event.target.files;
//iterate files since 'multiple' may be specified on the element
for (var i = 0;i<files.length;i++) {
//emit event upward
scope.$emit("fileSelected", { file: files[i] });
}
});
}
};
In the directive we ensure a new scope is created and then listen for changes made to the file input element. When changes are detected with emit an event to all ancestor scopes (upward) with the file object as a parameter.
In your controller:
$scope.files = [];
//listen for the file selected event
$scope.$on("fileSelected", function (event, args) {
$scope.$apply(function () {
//add the file object to the scope's files collection
$scope.files.push(args.file);
});
});
Then in your ajax call:
data: { model: $scope.model, files: $scope.files }
http://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/
Destroy the datatable first and then draw the datatable.
$('#table1').DataTable().destroy();
$('#table1').find('tbody').append("<tr><td><value1></td><td><value1></td></tr>");
$('#table1').DataTable().draw();
You could store key/values in Redis differently to achieve this, by just adding a prefix or namespace to your keys when you store them e.g. "hset_"
Get a key/value GET hset_key
equals to HGET hset key
Add a key/value SET hset_key value
equals to HSET hset key
Get all keys KEYS hset_*
equals to HGETALL hset
Get all vals should be done in 2 ops, first get all keys KEYS hset_*
then get the value for each key
Add a key/value with TTL or expire which is the topic of question:
SET hset_key value
EXPIRE hset_key
Note: KEYS
will lookup up for matching the key in the whole database which may affect on performance especially if you have big database.
Note:
KEYS
will lookup up for matching the key in the whole database which may affect on performance especially if you have big database. while SCAN 0 MATCH hset_*
might be better as long as it doesn't block the server but still performance is an issue in case of big database.
You may create a new database for storing separately these keys that you want to expire especially if they are small set of keys.
Thanks to @DanFarrell who highlighted the performance issue related to
KEYS
Use numpy.concatenate(list1 , list2)
or numpy.append()
Look into the thread at Append a NumPy array to a NumPy array.
Probably the shortest version:
[System.Collections.ArrayList]$someArray
It is also faster because it does not call relatively expensive New-Object
.
A very good plugin management system to use. The included vimrc file is good enough for python programming and can be easily configured to your needs. See http://spf13.com/project/spf13-vim/
Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour.
function func(){
return true;
}
isBool = func();
console.log(typeof (isBool)); // output - string
let isBool = func();
console.log(typeof (isBool)); // output - boolean
fout=open("out.csv","a")
for num in range(1,201):
for line in open("sh"+str(num)+".csv"):
fout.write(line)
fout.close()
You'll be wanting to use glob()
Example:
$files = glob('/path/to/dir/*.xml');
I have used 680px in commercial reports to print on A4 pages since 1998. The 700px could not fit correctly depend of size of margins. Modern browsers can shrink page to fit page on printer, but if you use 680 pixels you will print correctly in almost any browsers.
That is HTML to you Run code snippet and see de result:
window.print();
_x000D_
<table width=680 border=1 cellpadding=20 cellspacing=0>_x000D_
<tr><th>#</th><th>name</th></tr>_x000D_
<tr align=center><td>1</td><td>DONALD TRUMP</td></tr>_x000D_
<tr align=center><td>2</td><td>BARACK OBAMA</td></tr>_x000D_
</table>
_x000D_
JSFiddle:
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set
is needed because TextRange
is a class, so hyperLinkText
is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.
I use this version
<style><%@include file="/WEB-INF/css/style.css"%></style>
This lookup only features exact matches. If you have an extra space in one of the columns or something similar it will not recognize it.
There was a really nice post on the Spring Blog from Keith Donald detailing howto Obtain Spring 3 Aritfacts with Maven, with comments detailing when you'd need each of the dependencies...
<!-- Shared version number properties -->
<properties>
<org.springframework.version>3.0.0.RELEASE</org.springframework.version>
</properties>
<!-- Core utilities used by other modules.
Define this if you use Spring Utility APIs
(org.springframework.core.*/org.springframework.util.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Expression Language (depends on spring-core)
Define this if you use Spring Expression APIs
(org.springframework.expression.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Bean Factory and JavaBeans utilities (depends on spring-core)
Define this if you use Spring Bean APIs
(org.springframework.beans.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Aspect Oriented Programming (AOP) Framework
(depends on spring-core, spring-beans)
Define this if you use Spring AOP APIs
(org.springframework.aop.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Application Context
(depends on spring-core, spring-expression, spring-aop, spring-beans)
This is the central artifact for Spring's Dependency Injection Container
and is generally always defined-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Various Application Context utilities, including EhCache, JavaMail, Quartz,
and Freemarker integration
Define this if you need any of these integrations-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Transaction Management Abstraction
(depends on spring-core, spring-beans, spring-aop, spring-context)
Define this if you use Spring Transactions or DAO Exception Hierarchy
(org.springframework.transaction.*/org.springframework.dao.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- JDBC Data Access Library
(depends on spring-core, spring-beans, spring-context, spring-tx)
Define this if you use Spring's JdbcTemplate API
(org.springframework.jdbc.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Object-to-Relation-Mapping (ORM) integration with Hibernate, JPA and iBatis.
(depends on spring-core, spring-beans, spring-context, spring-tx)
Define this if you need ORM (org.springframework.orm.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Object-to-XML Mapping (OXM) abstraction and integration with JAXB, JiBX,
Castor, XStream, and XML Beans.
(depends on spring-core, spring-beans, spring-context)
Define this if you need OXM (org.springframework.oxm.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Web application development utilities applicable to both Servlet and
Portlet Environments
(depends on spring-core, spring-beans, spring-context)
Define this if you use Spring MVC, or wish to use Struts, JSF, or another
web framework with Spring (org.springframework.web.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring MVC for Servlet Environments
(depends on spring-core, spring-beans, spring-context, spring-web)
Define this if you use Spring MVC with a Servlet Container such as
Apache Tomcat (org.springframework.web.servlet.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring MVC for Portlet Environments
(depends on spring-core, spring-beans, spring-context, spring-web)
Define this if you use Spring MVC with a Portlet Container
(org.springframework.web.portlet.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Support for testing Spring applications with tools such as JUnit and TestNG
This artifact is generally always defined with a 'test' scope for the
integration testing framework and unit testing stubs-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
Here's a solution using C#:
void DrawCirclePoints(int points, double radius, Point center)
{
double slice = 2 * Math.PI / points;
for (int i = 0; i < points; i++)
{
double angle = slice * i;
int newX = (int)(center.X + radius * Math.Cos(angle));
int newY = (int)(center.Y + radius * Math.Sin(angle));
Point p = new Point(newX, newY);
Console.WriteLine(p);
}
}
Sample output from DrawCirclePoints(8, 10, new Point(0,0));
:
{X=10,Y=0}
{X=7,Y=7}
{X=0,Y=10}
{X=-7,Y=7}
{X=-10,Y=0}
{X=-7,Y=-7}
{X=0,Y=-10}
{X=7,Y=-7}
Good luck!
This worked for me (using WSL)
sudo /etc/init.d/redis start
(for any other service, check the init.d folder for filenames)
The View::make
function takes 3 arguments which according to the documentation are:
public View make(string $view, array $data = array(), array $mergeData = array())
In your case, the compact('selections')
is a 4th argument. It doesn't pass to the view and laravel throws an exception.
On the other hand, you can use with()
as many time as you like. Thus, this will work:
return View::make('gameworlds.mygame')
->with(compact('fixtures'))
->with(compact('teams'))
->with(compact('selections'));
This tool saved me a lot, since I have no Admin permission on my machine and already had nodejs installed. For some reason the configuration on my network does not give me access to other machines just pointing the IP on the browser.
# Using a local.dev vhost
$ browser-sync start --proxy
# Using a local.dev vhost with PORT
$ browser-sync start --proxy local.dev:8001
# Using a localhost address
$ browser-sync start --proxy localhost:8001
# Using a localhost address in a sub-dir
$ browser-sync start --proxy localhost:8080/site1
Take a look at Generic Lists.
I just spent some serious time figuring some things out with React and scrolling events / positions - so for those still looking, here's what I found:
The viewport height can be found by using window.innerHeight or by using document.documentElement.clientHeight. (Current viewport height)
The height of the entire document (body) can be found using window.document.body.offsetHeight.
If you're attempting to find the height of the document and know when you've hit the bottom - here's what I came up with:
if (window.pageYOffset >= this.myRefII.current.clientHeight && Math.round((document.documentElement.scrollTop + window.innerHeight)) < document.documentElement.scrollHeight - 72) {
this.setState({
trueOrNot: true
});
} else {
this.setState({
trueOrNot: false
});
}
}
(My navbar was 72px in fixed position, thus the -72 to get a better scroll-event trigger)
Lastly, here are a number of scroll commands to console.log(), which helped me figure out my math actively.
console.log('window inner height: ', window.innerHeight);
console.log('document Element client hieght: ', document.documentElement.clientHeight);
console.log('document Element scroll hieght: ', document.documentElement.scrollHeight);
console.log('document Element offset height: ', document.documentElement.offsetHeight);
console.log('document element scrolltop: ', document.documentElement.scrollTop);
console.log('window page Y Offset: ', window.pageYOffset);
console.log('window document body offsetheight: ', window.document.body.offsetHeight);
Whew! Hope it helps someone!
An answer taken from ChristopheD here: https://stackoverflow.com/a/2500023/1225603
r = "456results string789"
s = ''.join(x for x in r if x.isdigit())
print int(s)
456789
Use which(mydata_2$height_chad1 == 2585)
Short example
df <- data.frame(x = c(1,1,2,3,4,5,6,3),
y = c(5,4,6,7,8,3,2,4))
df
x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4
which(df$x == 3)
[1] 4 8
length(which(df$x == 3))
[1] 2
count(df, vars = "x")
x freq
1 1 2
2 2 1
3 3 2
4 4 1
5 5 1
6 6 1
df[which(df$x == 3),]
x y
4 3 7
8 3 4
As Matt Weller pointed out, you can use the length
function.
The count
function in plyr
can be used to return the count of each unique column value.
I like to do this with sed. In you case:
for x in DET01-*.dat; do
echo $x | sed -r 's/DET01-ABC-(.+)\.dat/mv -v "\0" "DET01-XYZ-\1.dat"/'
done | sh -e
It is best to omit the "sh -e" part first to see what will be executed.
while on branch master:
git reset --hard origin/master
then do some clean up with git gc
(more about this in the man pages)
Update: You will also probably need to do a git fetch origin
(or git fetch origin master
if you only want that branch); it should not matter if you do this before or after the reset. (Thanks @eric-walker)
It is not cp -i
. If you do not want to be asked for confirmation,
it is cp -n
; for example:
cp -n src dest
Or in case of directories/folders is:
cp -nr src_dir dest_dir
Elegant easy solution using jQuery.
<script>
function call() {
var body = $("html, body");
body.stop().animate({scrollTop:0}, 500, 'swing', function() {
});
}
</script>
and in your html :
<div onclick="call()"><img src="../img/[email protected]"></div>
Removing the ca-certificates-java package and installing it again worked for me (Ubuntu MATE 17.10 (Artful Aardvark)).
sudo dpkg --purge --force-depends ca-certificates-java
sudo apt-get install ca-certificates-java
Thank you, jdstrand: Comment 1 for bug 983302, Re: ca-certificates-java fails to install Java cacerts on Oneiric Ocelot.
You need to use a constant.
CONST NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) As Zombies
or if you want to use a variable you have to do it this way:
Dim NumberOfZombies As Integer
NumberOfZombies = 20000
Dim Zombies() As Zombies
ReDim Zombies(NumberOfZombies)
Will the username and password be automatically SSL encrypted? Is the same true for GETs and POSTs
Yes, yes yes.
The entire communication (save for the DNS lookup if the IP for the hostname isn't already cached) is encrypted when SSL is in use.
I would do this a little differently so that it scales without having to define every case:
select t.range as [score range], count(*) as [number of occurences]
from (
select FLOOR(score/10) as range
from scores) t
group by t.range
Not tested, but you get the idea...
Use proper escaping: string.split("\\|")
Or, in Java 5+, use the helper Pattern.quote()
which has been created for exactly this purpose:
string.split(Pattern.quote("|"))
which works with arbitrary input strings. Very useful when you need to quote / escape user input.
try this
json = $.grep(newcurrPayment.paymentTypeInsert, function (el, idx) { return el.FirstName == "Test1" }, true)
http://joda-time.sourceforge.net/quickstart.html
Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:
* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class
Do note that on newer Apache versions the RewriteLog
and RewriteLogLevel
have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):
AH00526: Syntax error on line xx of path/to/config/file.conf: Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`
Instead, you're now supposed to use the general LogLevel
directive, with a level of trace1
up to trace8
. 'debug' didn't display any rewrite messages in the log for me.
Example: LogLevel warn rewrite:trace3
For the official documentation, see here.
Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.
[DllImport ( "Shlwapi.dll", CharSet = CharSet.Auto )]
public static extern long StrFormatByteSize (
long fileSize
, [MarshalAs ( UnmanagedType.LPTStr )] StringBuilder buffer
, int bufferSize );
/// <summary>
/// Converts a numeric value into a string that represents the number expressed as a size value in bytes, kilobytes, megabytes, or gigabytes, depending on the size.
/// </summary>
/// <param name="filelength">The numeric value to be converted.</param>
/// <returns>the converted string</returns>
public static string StrFormatByteSize (long filesize) {
StringBuilder sb = new StringBuilder( 11 );
StrFormatByteSize( filesize, sb, sb.Capacity );
return sb.ToString();
}
From: http://www.pinvoke.net/default.aspx/shlwapi/StrFormatByteSize.html
TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.
http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx
Install gcc.
If you're on linux, use the package manager.
If you're on Windows, use MinGW.
http://www.bootply.com/3iSOTAyumP in this example the button for collapse was not clickable because the .navbar-brand was in front.
http://www.bootply.com/RfnEgu45qR there is an updated version where the collapse buttons is actually clickable.
Try:
select concat(first_name,last_name) as "Name" from test.student
or, better:
select concat(first_name," ",last_name) as "Name" from test.student
Your logic is backwards.
SELECT
*
FROM
`test_table`
WHERE
start_date NOT BETWEEN CAST('2009-12-15' AS DATE) and CAST('2010-01-02' AS DATE)
AND end_date NOT BETWEEN CAST('2009-12-15' AS DATE) and CAST('2010-01-02' AS DATE)
When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.
But there are more important differences on the receiving side of things. When the receiver does a recv
(or read
) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.
Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.
In function post():
todo.author = users.get_current_user()
So, to get str(todo.author), you need str(users.get_current_user()). What is returned by get_current_user() function ?
If it is an object, check does it contain a str()" function?
I think the error lies there.
var romanNumerals = [
['M', 1000],['CM', 900],['D', 500],['CD', 400],['C', 100],['XC', 90],['L', 50],['XL', 40],['X', 10],['IX', 9],['V', 5],['IV', 4],['I', 1]];
RomanNumerals = {
romerate: function(foo) {
var bar = '';
romanNumerals.forEach(function(buzz) {
while (foo >= buzz[1]) {
bar += buzz[0];
foo -= buzz[1];
}
});
return bar;
},
numerate: function(x) {
var y = 0;
romanNumerals.forEach(function(z) {
while (x.substr(0, z[0].length) == z[0]) {
x = x.substr(z[0].length);
y += z[1];
}
});
return y;
}
};
In 2018:
<input type="number" pattern="\d*">
is working for both Android and iOS.
I tested on Android (^4.2) and iOS (11.3)
This might work for you (GNU sed):
sed -n ':a;/regexp/{n;h;p;x;ba}' file
Use seds grep-like option -n
and if the current line contains the required regexp replace the current line with the next, copy that line to the hold space (HS), print the line, swap the pattern space (PS) for the HS and repeat.
Try:
In the controller:
ViewBag.Accounts= new SelectList(db.Accounts, "AccountId", "AccountName");
In the View:
@Html.DropDownList("AccountId", (IEnumerable<SelectListItem>)ViewBag.Accounts, null, new { @class ="form-control" })
or you can replace the "null" with whatever you want display as default selector, i.e. "Select Account".
TL;DR
You should use FLUSH PRIVILEGES;
only if you modify the grant tables directly using statements such as INSERT
, UPDATE
, or DELETE
.
Apart from sp_who
, you can also use the "undocumented" sp_who2
system stored procedure which gives you more detailed information. See Difference between sp_who and sp_who2.
Use this 'Split' function:
CREATE OR REPLACE FUNCTION Split (p_str varchar2) return sys_refcursor is
v_res sys_refcursor;
begin
open v_res for
WITH TAB AS
(SELECT p_str STR FROM DUAL)
select substr(STR, instr(STR, ',', 1, lvl) + 1, instr(STR, ',', 1, lvl + 1) - instr(STR, ',', 1, lvl) - 1) name
from
( select ',' || STR || ',' as STR from TAB ),
( select level as lvl from dual connect by level <= 100 )
where lvl <= length(STR) - length(replace(STR, ',')) - 1;
return v_res;
end;
You can't use this function in select statement like you described in question, but I hope you will find it still useful.
EDIT: Here are steps you need to do. 1. Create Object: create or replace type empy_type as object(value varchar2(512)) 2. Create Type: create or replace type t_empty_type as table of empy_type 3. Create Function:
CREATE OR REPLACE FUNCTION Split (p_str varchar2) return sms.t_empty_type is
v_emptype t_empty_type := t_empty_type();
v_cnt number := 0;
v_res sys_refcursor;
v_value nvarchar2(128);
begin
open v_res for
WITH TAB AS
(SELECT p_str STR FROM DUAL)
select substr(STR, instr(STR, ',', 1, lvl) + 1, instr(STR, ',', 1, lvl + 1) - instr(STR, ',', 1, lvl) - 1) name
from
( select ',' || STR || ',' as STR from TAB ),
( select level as lvl from dual connect by level <= 100 )
where lvl <= length(STR) - length(replace(STR, ',')) - 1;
loop
fetch v_res into v_value;
exit when v_res%NOTFOUND;
v_emptype.extend;
v_cnt := v_cnt + 1;
v_emptype(v_cnt) := empty_type(v_value);
end loop;
close v_res;
return v_emptype;
end;
Then just call like this:
SELECT * FROM (TABLE(split('a,b,c,d,g')))
I suggest that you add
#!/usr/bin/env python
instead of #!/usr/bin/python
at the top of the file. The reason for this is that the python installation may be in different folders in different distros or different computers. By using env
you make sure that the system finds python and delegates the script's execution to it.
As said before to make the script executable, something like:
chmod u+x name_of_script.py
should do.
OneToOneField (Example: one car has one owner) ForeignKey(OneToMany) (Example: one restaurant has many items)
Seems change
is changed to isChange
for gradle version 6.3, kotlin version 1.3.70, Groovy 2.5.10
The working configuration is
implementation("com.sample:commons:1.0.0-SNAPSHOT") {
isChanging = true
}
Also, run this command to fetch the latest
./gradlew assemble --refresh-dependencies
print() has a built in parameter "end" that is by default set to "\n" Calling print("This is America") is actually calling print("This is America", end = "\n"). An easy way to do is to call print("This is America", end ="")
if you're like me who is using AWS and CloudFront, here's how to solve the issue. it's similar to what others have shared except you don't use your domain's crt file, just what comodo emailed you.
cat COMODORSADomainValidationSecureServerCA.crt COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt > ssl-bundle.crt
this worked for me and my site no longer displays the ssl warning on chrome in android.
Simpler:
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "DoPostBack", "__doPostBack(sender, e)", true);
Nice detailed answer. just wanted to add one more thing which will definitely help others to see the UTF-8 encoding on URLs in action .
Follow the steps below to enable UTF-8 encoding on URLs in firefox.
type "about:config" in the address bar.
Use the filter input type to search for "network.standard-url.encode-query-utf8" property.
UTF-8 encoding on URLs works by default in IE6/7/8 and chrome.
The onPause()
and onResume()
methods are called when the application is brought to the background and into the foreground again. However, they are also called when the application is started for the first time and before it is killed. You can read more in Activity.
There isn't any direct approach to get the application status while in the background or foreground, but even I have faced this issue and found the solution with onWindowFocusChanged
and onStop
.
For more details check here Android: Solution to detect when an Android app goes to the background and come back to the foreground without getRunningTasks or getRunningAppProcesses.
If a variable is not set then it is NULL
and if you try to divide something by null you will get a divides by zero error
Read about using docstrings in your Python code.
As per the Python docstring conventions:
The docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.
There will be no golden rule, but rather provide comments that mean something to the other developers on your team (if you have one) or even to yourself when you come back to it six months down the road.
For Windows 10 the event ID for lock=4800 and unlock=4801.
As it says in the answer provided by Mario and User 00000, you will need to enable logging of lock and unlock events by using their method described above by running gpedit.msc and navigating to the branch they indicated:
Computer Configuration -> Windows Settings -> Security Settings -> Advanced Audit Policy Configuration -> System Audit Policies - Local Group Policy Object -> Logon/Logoff -> Audit Other Login/Logoff
Enable for both success and failure events.
After enabling logging of those events you can filter for Event ID 4800 and 4801 directly.
This method works for Windows 10 as I just used it to filter my security logs after locking and unlocking my computer.
You can use substr
:
echo substr('a,b,c,d,e,', 0, -1);
# => 'a,b,c,d,e'
You could insert input fields without "name" attribute:
<input type="text" id="in-between" />
Or you could simply remove them once the form is submitted (in jQuery
):
$("form").submit(function() {
$(this).children('#in-between').remove();
});
You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)
So to insert Employee / Department pairs that do not currently exist you might try something like the following.
CREATE TRIGGER trig_Update_Employee
ON [EmployeeResult]
FOR INSERT
AS
Begin
Insert into Employee (Name, Department)
Select Distinct i.Name, i.Department
from Inserted i
Left Join Employee e
on i.Name = e.Name and i.Department = e.Department
where e.Name is null
End
Use the matplotlib.arrow() function and set the parameters head_length and head_width to zero to don't get an "arrow-end". The connections between the different points can be simply calculated using vector addition with: A = [1,2], B=[3,4] --> Connection between A and B is B-A = [2,2]. Drawing this vector starting at the tip of A ends at the tip of B.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
A = np.array([[10,8],[1,2],[7,5],[3,5],[7,6],[8,7],[9,9],[4,5],[6,5],[6,8]])
fig = plt.figure(figsize=(10,10))
ax0 = fig.add_subplot(212)
ax0.scatter(A[:,0],A[:,1])
ax0.arrow(A[0][0],A[0][1],A[1][0]-A[0][0],A[1][1]-A[0][1],width=0.02,color='red',head_length=0.0,head_width=0.0)
ax0.arrow(A[2][0],A[2][1],A[9][0]-A[2][0],A[9][1]-A[2][1],width=0.02,color='red',head_length=0.0,head_width=0.0)
ax0.arrow(A[4][0],A[4][1],A[6][0]-A[4][0],A[6][1]-A[4][1],width=0.02,color='red',head_length=0.0,head_width=0.0)
plt.show()
Just Run in your terminal.
composer dump-autoload
To initialize to current date, you could do something like:
Date firstDate = new Date();
To get it from String, you could use SimpleDateFormat like:
String dateInString = "10-Jan-2016";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
//handle exception if date is not in "dd-MMM-yyyy" format
}
Visual Studio 2019 with CMake
Add the following to CMakeLists.txt
:
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
Use the %lf
format specifier to read a double:
double a;
scanf("%lf",&a);
Wikipedia has a decent reference for available format specifiers.
You'll need to use the %lf
format specifier to print out the results as well:
printf("%lf %lf",a,b);
You can find out what Git does with a file by seeing what it does when you add it to the index. The index is like a pre-commit. With the index committed, you can use git checkout
to bring everything that was in the index back into the working directory. So, what does Git do when you add a symbolic link to the index?
To find out, first, make a symbolic link:
$ ln -s /path/referenced/by/symlink symlink
Git doesn't know about this file yet. git ls-files
lets you inspect your index (-s
prints stat
-like output):
$ git ls-files -s ./symlink
[nothing]
Now, add the contents of the symbolic link to the Git object store by adding it to the index. When you add a file to the index, Git stores its contents in the Git object store.
$ git add ./symlink
So, what was added?
$ git ls-files -s ./symlink
120000 1596f9db1b9610f238b78dd168ae33faa2dec15c 0 symlink
The hash is a reference to the packed object that was created in the Git object store. You can examine this object if you look in .git/objects/15/96f9db1b9610f238b78dd168ae33faa2dec15c
in the root of your repository. This is the file that Git stores in the repository, that you can later check out. If you examine this file, you'll see it is very small. It does not store the contents of the linked file. To confirm this, print the contents of the packed repository object with git cat-file
:
$ git cat-file -p 1596f9db1b9610f238b78dd168ae33faa2dec15c
/path/referenced/by/symlink
(Note 120000
is the mode listed in ls-files
output. It would be something like 100644
for a regular file.)
But what does Git do with this object when you check it out from the repository and into your filesystem? It depends on the core.symlinks
config. From man git-config
:
core.symlinks
If false, symbolic links are checked out as small plain files that contain the link text.
So, with a symbolic link in the repository, upon checkout you either get a text file with a reference to a full filesystem path, or a proper symbolic link, depending on the value of the core.symlinks
config.
Either way, the data referenced by the symlink is not stored in the repository.