It is because of the endlines in each lines. Use the chomp method in ruby to delete the endline '\n' or 'r' at the end.
line_num=0
File.open('xxx.txt').each do |line|
print "#{line_num += 1} #{line.chomp}"
end
Just like any other text file, .js
files have specific encodings they are saved in. This message means you are saving the .js
file with a non-UTF8 encoding (probably ASCII), and so your non-ASCII characters never even make it to the disk.
That is, the problem is not at the level of HTML or <meta charset>
or Content-Type
headers, but instead a very basic issue of how your text file is saved to disk.
To fix this, you'll need to change the encoding that Dreamweaver saves files in. It looks like this page outlines how to do so; choose UTF8 without saving a Byte Order Mark (BOM). This Super User answer (to a somewhat-related question) even includes screenshots.
This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.
Thank you for planting a seed, Cel! I've been struggling with this for hours, finally got it. I was counting a text field, oops, calculation failed.
Created 2 helper columns in my raw data, each resulting in 1 if condition met, 0 if not. Then pulled each into a pivot column, mine are called, "Inbd" (for Inbound), "Back", where "Back" is a return to sending facility, so in reality the total is one trip, not 2 trips, i.e., back is a subset of inbound and not every inbd has a back (obviously). Trying to calculate in the pivot table so I can sort on the field the rate of back to inbound for each sending facility.
For my calculated field I used: =IFERROR(IF(Pvt_Back>0,Pvt_Back/Pvt_Inbd,0),0)
So: if we sent back to sending some number of times greater than 0, divide Back/Inbd to give me a rate; if equal to 0, then 0; if Inbd = 0, then 0 to avoid Div/0 error.
Thanks again!! :)
<xsl:value-of select="name(.)" /> : <xsl:value-of select="."/>
I ran into a lot of issues when trying to figure this out. Here is my setup,
Dev Env : Windows 10, Java : 1.8.0_25, Spring Boot : 2.0.3.RELEASE, Spring : 5.0.7.RELEASE
What I found is spring is sticking with the concept "Sensible defaults for configuration". What this translates in to is, you have to have all your property files as part of your war file. Once in there, you can then override them using the "--spring.config.additional-location" command line property to point to external property files. But this will NOT WORK if the property files are not part of the original war file.
Demo code: https://github.com/gselvara/spring-boot-property-demo/tree/master
mkdir -p sam
You can use the following rule in .htaccess to rewrite a subdomain to a subfolder:
RewriteEngine On
# If the host is "sub.domain.com"
RewriteCond %{HTTP_HOST} ^sub.domain.com$ [NC]
# Then rewrite any request to /folder
RewriteRule ^((?!folder).*)$ /folder/$1 [NC,L]
Line-by-line explanation:
RewriteEngine on
The line above tells the server to turn on the engine for rewriting URLs.
RewriteCond %{HTTP_HOST} ^sub.domain.com$ [NC]
This line is a condition for the RewriteRule where we match against the HTTP host using a regex pattern. The condition says that if the host is sub.domain.com then execute the rule.
RewriteRule ^((?!folder).*)$ /folder/$1 [NC,L]
The rule matches http://sub.domain.com/foo and internally redirects it to http://sub.domain.com/folder/foo.
Replace sub.domain.com with your subdomain and folder with name of the folder you want to point your subdomain to.
Out of memory in android application is very common if we not handle the bitmap properly, The solution for the problem would be
if(imageBitmap != null) {
imageBitmap.recycle();
imageBitmap = null;
}
System.gc();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
imageBitmap = BitmapFactory.decodeFile(URI, options);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(imageBitmap, 200, 200, true);
imageView.setImageBitmap(scaledBitmap);
In the above code Have just tried to recycle the bitmap which will allow you to free up the used memory space ,so out of memory may not happen.I have tried it worked for me.
If still facing the problem you can also add these line as well
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
options.inPurgeable = true;
for more information take a look at this link
NOTE: Due to the momentary "pause" caused by performing gc, it is not recommended to do this before each bitmap allocation.
Optimum design is:
Free all bitmaps that are no longer needed, by the if / recycle / null
code shown. (Make a method to help with that.)
System.gc();
Allocate the new bitmaps.
type
%matplotlib qt
when you want graphs in a separate window and
%matplotlib inline
when you want an inline plot
SQL 2008
Radim Köhler's answer works, but here is a shorter version:
select top 20 * from
(
select *,
ROW_NUMBER() OVER (ORDER BY columnid) AS ROW_NUM
from tablename
) x
where ROW_NUM>10
a <div> is a logical division in your content, semantically this would be my first choice if I wanted to group the heading with the list:
<div class="mydiv">
<h3>The heading</h3>
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div>
then you can use the following css to style everything together as one unit
.mydiv{}
.mydiv h3{}
.mydiv ul{}
.mydiv ul li{}
etc...
The standard Pinterest button code (which you can generate here), is an <a>
tag wrapping an <img>
of the Pinterest button.
If you don't include the pinit.js
script on your page, this <a>
tag will work "as-is". You could improve the experience by registering your own click handler on these tags that opens a new window with appropriate dimensions, or at least adding target="_blank"
to the tag to make it open clicks in a new window.
The tag syntax would look like:
<a href="http://pinterest.com/pin/create/button/?url={URI-encoded URL of the page to pin}&media={URI-encoded URL of the image to pin}&description={optional URI-encoded description}" class="pin-it-button" count-layout="horizontal">
<img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" />
</a>
If using the JavaScript versions of sharing buttons are ruining your page load times, you can improve your site by using asynchronous loading methods. For an example of doing this with the Pinterest button, check out my GitHub Pinterest button project with an improved HTML5 syntax.
this is simple way to do push notification for all browser https://pushjs.org
Push.create("Hello world!", {
body: "How's it hangin'?",
icon: '/icon.png',
timeout: 4000,
onClick: function () {
window.focus();
this.close();
}
});
You can get a set of commits by using pick-axe.
git log -S'the line from your file' -- path/to/your/file.txt
This will give you all of the commits that affected that text in that file. If the file was renamed at some point, you can add --follow-parent.
If you would like to inspect the commits at each of these edits, you can pipe that result to git show:
git log ... | xargs -n 1 git show
Press the start button in visual studio. Then go to the location where your solution is stored and open the folder of your main project then the bin folder. If your application was running in debug mode then go to the debug folder. If running in release mode then go to the release folder. You should find your exe there.
I have a test application set up using JPA/Hibernate & Spring, and my configuration mirrors yours with the exception that I create a datasource and inject it into the EntityManagerFactory, and moved the datasource specific properties out of the persistenceUnit and into the datasource. With these two small changes, my EM gets injected properly.
I got it:
string clean = Regex.Replace(q, @"[^a-zA-Z0-9\s]", string.Empty);
Didn't know you could put \s in the brackets
Use the styles
left: 0px;
or/and
right: 0px;
or/and
top: 0px;
or/and
bottom: 0px;
I think for most cases that will do the job
There is also multipanelfigure package that is worth to mention. See also this answer.
library(ggplot2)
theme_set(theme_bw())
q1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
q2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
q3 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec))
q4 <- ggplot(mtcars) + geom_bar(aes(carb))
library(magrittr)
library(multipanelfigure)
figure1 <- multi_panel_figure(columns = 2, rows = 2, panel_label_type = "none")
# show the layout
figure1
figure1 %<>%
fill_panel(q1, column = 1, row = 1) %<>%
fill_panel(q2, column = 2, row = 1) %<>%
fill_panel(q3, column = 1, row = 2) %<>%
fill_panel(q4, column = 2, row = 2)
figure1
# complex layout
figure2 <- multi_panel_figure(columns = 3, rows = 3, panel_label_type = "upper-roman")
figure2
figure2 %<>%
fill_panel(q1, column = 1:2, row = 1) %<>%
fill_panel(q2, column = 3, row = 1) %<>%
fill_panel(q3, column = 1, row = 2) %<>%
fill_panel(q4, column = 2:3, row = 2:3)
figure2
Created on 2018-07-06 by the reprex package (v0.2.0.9000).
Be careful when exporting from and importing to different MySQL versions as the mysql tables may have different columns. Grant privileges may fail to work if you're out of luck. I created this script (mysql_export_grants.sql ) to dump the grants for importing into the new database, just in case:
#!/bin/sh
stty -echo
printf 'Password: ' >&2
read PASSWORD
stty echo
printf "\n"
if [ -z "$PASSWORD" ]; then
echo 'No password given!'
exit 1
fi
MYSQL_CONN="-uroot -p$PASSWORD"
mysql ${MYSQL_CONN} --skip-column-names -A -e"SELECT CONCAT('SHOW GRANTS FOR ''',user,'''@''',host,''';') FROM mysql.user WHERE user<>''" | mysql ${MYSQL_CONN} --skip-column-names -A | sed 's/$/;/g'
Based on post by toster-cx and other interesting posts on this page, I got insight on how to configure and solve my problem. I had similar issue where I wished that Disk Cleanup utility runs every week twice on Monday and Thursday during lunch hours (say 2 pm). However, this required elevated rights.
Sharing batch file which might help other beginners like me -
@echo off
echo Welcome to scheduling 'PC Maintenance Activity'
ping localhost -n 3 >nul
echo -- Step - 1 of 3 : Please give 'Admin' rights on next screen
ping localhost -n 5 >nul
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit)
cls
echo -- Step - 2 of 3 : In next screen, select temp areas for cleaning
during routine scheduled activity
ping localhost -n 3 >nul
C:\Windows\System32\cleanmgr.exe /sageset:112
cls
echo Now scheduling maintenance activity...
SchTasks /Create /SC WEEKLY /D MON,THU /TN PC_Cleanup /TR
"C:\Windows\System32\cleanmgr.exe "/sagerun:112 /ST 14:00
cls
echo -- Thanks for your co-operation --
echo -- Maintenance activity is scheduled for --
echo -- Every Monday and Thursday at 2 pm --
ping localhost -n 10 >nul
Thanks a lot for this forum and Rems POST here [https://www.petri.com/forums/forum/windows-scripting/general-scripting/32313-schtasks-exe-need-to-pass-parameters-to-script][1]
His post helped for configuring optional argument while scheduling the task.
OK realized a mistake .. it has to be /:id/:id2
Anyway didn't find this in any tutorial or other StackOverflow question.
@RouteConfig([{path: '/component/:id/:id2',name: 'MyCompB', component:MyCompB}])
export class MyCompA {
onClick(){
this._router.navigate( ['MyCompB', {id: "someId", id2: "another ID"}]);
}
}
For those whom the current answers didn't work can try this: (Tested on mac os)
mysql -h localhost -u root -p --protocol=TCP
After this a password will be asked from you and you should use your OS user password. then when you got into MySQL you can run:
select Host, User from mysql.user;
and you should see
MySQL [(none)]> select Host, User from mysql.user;
+-----------+------------------+
| Host | User |
+-----------+------------------+
| localhost | mysql.infoschema |
| localhost | mysql.session |
| localhost | mysql.sys |
| localhost | root |
+-----------+------------------+
and from here you can change the configurations and edit the password or modify the grants.
Even same issue I faced, in browser it was showing compiled code. I have made below changes in webpack config file and it is working fine now.
devtool: '#inline-source-map',
debug: true,
and in loaders I kept babel-loader as first option
loaders: [
{
loader: "babel-loader",
include: [path.resolve(__dirname, "src")]
},
{ test: /\.js$/, exclude: [/app\/lib/, /node_modules/], loader: 'ng-annotate!babel' },
{ test: /\.html$/, loader: 'raw' },
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
},
{test: /\.less$/, loader: "style!css!less"},
{ test: /\.styl$/, loader: 'style!css!stylus' },
{ test: /\.css$/, loader: 'style!css' }
]
From menu, Code -> Comment with Line Commment. So simple.
Assuming that the items in your CheckedListBox are strings:
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if ((string)checkedListBox1.Items[i] == value)
{
checkedListBox1.SetItemChecked(i, true);
}
}
Or
int index = checkedListBox1.Items.IndexOf(value);
if (index >= 0)
{
checkedListBox1.SetItemChecked(index, true);
}
I came up with this function which does not mutate the original dictionary. This function also supports list of dictionaries too.
import functools
from typing import Union, Dict, List
def rename_dict_keys(
data: Union[Dict, List[Dict]], old_key: str, new_key: str
):
"""
This function renames dictionary keys
:param data:
:param old_key:
:param new_key:
:return: Union[Dict, List[Dict]]
"""
if isinstance(data, dict):
res = {k: v for k, v in data.items() if k != old_key}
try:
res[new_key] = data[old_key]
except KeyError:
raise KeyError(
"cannot rename key as old key '%s' is not present in data"
% old_key
)
return res
elif isinstance(data, list):
return list(
map(
functools.partial(
rename_dict_keys, old_key=old_key, new_key=new_key
),
data,
)
)
raise ValueError("expected type List[Dict] or Dict got '%s' for data" % type(data))
If you add and remove the innerHTML, all javascript, css and more will be loaded twice, and the events will fire twice (happened to me), is better hide content, using jQuery and css like this:
function printDiv(selector) {
$('body .site-container').css({display:'none'});
var content = $(selector).clone();
$('body .site-container').before(content);
window.print();
$(selector).first().remove();
$('body .site-container').css({display:''});
}
The div "site-container" contain all site, so you can call the function like:
printDiv('.someDiv');
In recent browsers you can use:
Object.keys(obj.Data).length
See MDN
For older browsers, use the for-in
loop in Michael Geary's answer.
If you're not too concerned with performance, you could always try listening on a port using the ServerSocket class. If it throws an exception odds are it's being used.
public static boolean isAvailable(int portNr) {
boolean portFree;
try (var ignored = new ServerSocket(portNr)) {
portFree = true;
} catch (IOException e) {
portFree = false;
}
return portFree;
}
EDIT: If all you're trying to do is select a free port then new ServerSocket(0)
will find one for you.
Import namespace :
using System.Configuration;
Create ConfigurationElement Company :
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
ConfigurationElementCollection:
public class Companies
: ConfigurationElementCollection
{
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
and ConfigurationSection:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
and you must also register your new configuration section in web.config (app.config):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
then you load your config with
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
tl;dr; Excel does all of this natively - use filters and or tables
(http://office.microsoft.com/en-gb/excel-help/filter-data-in-an-excel-table-HA102840028.aspx)
You can open excel programatically through an oledb connection and execute SQL on the tables within the worksheet.
But you can do everything you are asking to do with no formulas just filters.
have a play around.. some things to note:
DO it with filters unless you are going to do it a lot or you want to automate importing data somewhere or something.. but for completeness:
A c# option:
OleDbConnection ExcelFile = new OleDbConnection( String.Format( "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES\"", filename));
ExcelFile.Open();
a handy place to start is to take a look at the schema as there may be more there than you think:
List<String> excelSheets = new List<string>();
// Add the sheet name to the string array.
foreach (DataRow row in dt.Rows) {
string temp = row["TABLE_NAME"].ToString();
if (temp[temp.Length - 1] == '$') {
excelSheets.Add(row["TABLE_NAME"].ToString());
}
}
then when you want to query a sheet:
OleDbDataAdapter da = new OleDbDataAdapter("select * from [" + sheet + "]", ExcelFile);
dt = new DataTable();
da.Fill(dt);
NOTE - Use Tables in excel!:
Excel has "tables" functionality that make data behave more like a table.. this gives you some great benefits but is not going to let you do every type of query.
http://office.microsoft.com/en-gb/excel-help/overview-of-excel-tables-HA010048546.aspx
For tabular data in excel this is my default.. first thing i do is click into the data then select "format as table" from the home section on the ribbon. this gives you filtering, and sorting by default and allows you to access the table and fields by name (e.g. table[fieldname] ) this also allows aggregate functions on columns e.g. max and average
For some reason
if (strictBounds.contains(map.getCenter())) return;
didnt work for me (maybe a southern hemisphere issue). I had to change it to:
function checkBounds() {
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if(x < minX || x > maxX || y < minY || y > maxY) {
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
}
}
Hope it will help someone.
No. The first returns a DOM element, or null, whereas the second always returns a jQuery object. The jQuery object will be empty if no element with the id of contents
was matched.
The DOM element returned by document.getElementById('contents')
allows you to do things such as change the .innerHTML
(or .value
) etc, however you'll need to use jQuery methods on the jQuery Object.
var contents = $('#contents').get(0);
Is more equivilent, however if no element with the id of contents
is matched, document.getElementById('contents')
will return null, but $('#contents').get(0)
will return undefined.
One benefit on using the jQuery object is that you won't get any errors if no elements were returned, as an object is always returned. However you will get errors if you try to perform operations on the null
returned by document.getElementById
This is what I used to accomplish to this:
System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, System.AppDomain.CurrentDomain.RelativeSearchPath ?? "");
In v2, there isn't anything built-in for that much vertical space, so you'll want to stick with a custom class. For smaller heights, I usually just throw a <div class="control-group">
around a button.
You may also be missing using namespace std;
Try this code.
<input type="button" value="Open Window"
onclick="window.open('http://www.google.com')">
if you use a negative translateX/Y
width and height are not necessary and the style is really short
#form_login {
left : 50%;
top : 50%;
position : absolute;
transform : translate(-50%, -50%);
}
_x000D_
<form id="form_login">
<p>
<input type="text" id="username" placeholder="username" />
</p>
<p>
<input type="password" id="password" placeholder="password" />
</p>
<p>
<input type="text" id="server" placeholder="server" />
</p>
<p>
<button id="submitbutton" type="button">Se connecter</button>
</p>
</form>
_x000D_
Alternatively you could use display: grid
(check the full page view)
body {
margin : 0;
padding : 0;
display : grid;
place-content : center;
min-height : 100vh;
}
_x000D_
<form id="form_login">
<p>
<input type="text" id="username" placeholder="username" />
</p>
<p>
<input type="password" id="password" placeholder="password" />
</p>
<p>
<input type="text" id="server" placeholder="server" />
</p>
<p>
<button id="submitbutton" type="button">Se connecter</button>
</p>
</form>
_x000D_
If you are using this in chrome/chromium browser(ex: in Ubuntu 14.04), You can use one of the below command to tackle this issue.
ThinkPad-T430:~$ google-chrome --allow-file-access-from-files
ThinkPad-T430:~$ google-chrome --allow-file-access-from-files fileName.html
ThinkPad-T430:~$ chromium-browser --allow-file-access-from-files
ThinkPad-T430:~$ chromium-browser --allow-file-access-from-files fileName.html
This will allow you to load the file in chrome or chromium. If you have to do the same operation for windows you can add this switch in properties of the chrome shortcut or run it from cmd
with the flag. This operation is not allowed in Chrome, Opera, Internet Explorer by default. By default it works only in firefox and safari. Hence using this command will help you.
Alternately you can also host it on any web server (Example:Tomcat-java,NodeJS-JS,Tornado-Python, etc) based on what language you are comfortable with. This will work from any browser.
Revised Answer (Feb 12, 2014)
the_world_is_flat=true
# ...do something interesting...
if [ "$the_world_is_flat" = true ] ; then
echo 'Be careful not to fall off!'
fi
Original Answer
Caveats: https://stackoverflow.com/a/21210966/89391
the_world_is_flat=true
# ...do something interesting...
if $the_world_is_flat ; then
echo 'Be careful not to fall off!'
fi
From: Using boolean variables in Bash
The reason the original answer is included here is because the comments before the revision on Feb 12, 2014 pertain only to the original answer, and many of the comments are wrong when associated with the revised answer. For example, Dennis Williamson's comment about bash builtin true
on Jun 2, 2010 only applies to the original answer, not the revised.
Have a better one based on @hypo 's answer
public class GrowLabel : Label {
private bool mGrowing;
public GrowLabel() {
this.AutoSize = false;
}
private void resizeLabel() {
if (mGrowing)
return;
try {
mGrowing = true;
int width = this.Parent == null ? this.Width : this.Parent.Width;
Size sz = new Size(this.Width, Int32.MaxValue);
sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
this.Height = sz.Height + Padding.Bottom + Padding.Top;
} finally {
mGrowing = false;
}
}
protected override void OnTextChanged(EventArgs e) {
base.OnTextChanged(e);
resizeLabel();
}
protected override void OnFontChanged(EventArgs e) {
base.OnFontChanged(e);
resizeLabel();
}
protected override void OnSizeChanged(EventArgs e) {
base.OnSizeChanged(e);
resizeLabel();
}
}
int width = this.Parent == null ? this.Width : this.Parent.Width;
this allows you to use auto-grow label when docked to a parent, e.g. a panel.
this.Height = sz.Height + Padding.Bottom + Padding.Top;
here we take care of padding for top and bottom.
Your call to text()
doesn't output anything because you inverted your x and your y:
plot(abs_losses, percent_losses,
main= "Absolute Losses vs. Relative Losses(in%)",
xlab= "Losses (absolute, in miles of millions)",
ylab= "Losses relative (in % of January´2007 value)",
col= "blue", pch = 19, cex = 1, lty = "solid", lwd = 2)
text(abs_losses, percent_losses, labels=namebank, cex= 0.7)
Now if you want to move your labels down, left, up or right you can add argument pos=
with values, respectively, 1, 2, 3 or 4. For instance, to place your labels up:
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=3)
You can of course gives a vector of value to pos
if you want some of the labels in other directions (for instance for Goldman_Sachs, UBS and Société_Generale since they are overlapping with other labels):
pos_vector <- rep(3, length(namebank))
pos_vector[namebank %in% c("Goldman_Sachs", "Societé_Generale", "UBS")] <- 4
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=pos_vector)
It is better to use eager loading when it is possible, because it optimizes the performance of your application.
ex-:
Eager loading
var customers= _context.customers.Include(c=> c.membershipType).Tolist();
lazy loading
In model customer has to define
Public virtual string membershipType {get; set;}
So when querying lazy loading is much slower loading all the reference objects, but eager loading query and select only the object which are relevant.
You could use a dynamic object. I think it has better readability than Tuple.
static void Main(string[] args){
var obj = GetMultipleValues();
Console.WriteLine(obj.Id);
Console.WriteLine(obj.Name);
}
private static dynamic GetMultipleValues() {
dynamic temp = new System.Dynamic.ExpandoObject();
temp.Id = 123;
temp.Name = "Lorem Ipsum";
return temp;
}
select tableA.id from tableA left outer join tableB on (tableA.id = tableB.id)
where tableB.id is null
order by tableA.id desc
If your db knows how to do index intersections, this will only touch the primary key index
I have struggled with this problem since I don’t know why my droplevel() function does not work. Work through several and learn that ‘a’ in your table is columns name and ‘b’, ‘c’ are index. Do like this will help
df.columns.name = None
df.reset_index() #make index become label
Please note that the tr -s ' '
option will not remove any single leading spaces. If your column is right-aligned (as with ps
pid)...
$ ps h -o pid,user -C ssh,sshd | tr -s " "
1543 root
19645 root
19731 root
Then cutting will result in a blank line for some of those fields if it is the first column:
$ <previous command> | cut -d ' ' -f1
19645
19731
Unless you precede it with a space, obviously
$ <command> | sed -e "s/.*/ &/" | tr -s " "
Now, for this particular case of pid numbers (not names), there is a function called pgrep
:
$ pgrep ssh
However, in general it is actually still possible to use shell functions in a concise manner, because there is a neat thing about the read
command:
$ <command> | while read a b; do echo $a; done
The first parameter to read, a
, selects the first column, and if there is more, everything else will be put in b
. As a result, you never need more variables than the number of your column +1.
So,
while read a b c d; do echo $c; done
will then output the 3rd column. As indicated in my comment...
A piped read will be executed in an environment that does not pass variables to the calling script.
out=$(ps whatever | { read a b c d; echo $c; })
arr=($(ps whatever | { read a b c d; echo $c $b; }))
echo ${arr[1]} # will output 'b'`
So we then end up with the answer by @frayser which is to use the shell variable IFS which defaults to a space, to split the string into an array. It only works in Bash though. Dash and Ash do not support it. I have had a really hard time splitting a string into components in a Busybox thing. It is easy enough to get a single component (e.g. using awk) and then to repeat that for every parameter you need. But then you end up repeatedly calling awk on the same line, or repeatedly using a read block with echo on the same line. Which is not efficient or pretty. So you end up splitting using ${name%% *}
and so on. Makes you yearn for some Python skills because in fact shell scripting is not a lot of fun anymore if half or more of the features you are accustomed to, are gone. But you can assume that even python would not be installed on such a system, and it wasn't ;-).
I think that people making decisions simply forgot about complex values, matrix algebra, set theory and other cases when overloading would allow to use the standard notation without building everything into the language. Anyway, only mathematically oriented software really benefits from such features. A generic customer application almost never needs them.
They arguments about the unnecessary obfuscation are obviously valid when a programmer defines some program-specific operator where it could be the function instead. A name of the function, when clearly visible, provides the hint that it does. Operator is a function without the readable name.
Java is generally designed about philosophy that some extra verbosity is not bad as it makes the code more readable. Constructs that do the same just have less code to type in used to be called a "syntax sugar" in the past. This is very different from the Python philosophy, for instance, where shorter is near always seen as better, even if providing less context for the second reader.
For me, it was really simple: I had a stale postmaster.pid
file.
Simply deleting and restarting postgres fixed it for me:
rm '/Users/<username>/Library/Application Support/Postgres/var-10/postmaster.pid'
I don't have a high enough reputation to comment on Gavin Simpson's answer, but I wanted to warn that there seems to be a difference in the default treatment of missing values between the standard syntax and the formula syntax for aggregate
.
#Create some data with missing values
a<-data.frame(day=rep(1,5),hour=c(1,2,3,3,4),val=c(1,NA,3,NA,5))
day hour val
1 1 1 1
2 1 2 NA
3 1 3 3
4 1 3 NA
5 1 4 5
#Standard syntax
aggregate(a$val,by=list(day=a$day,hour=a$hour),mean,na.rm=T)
day hour x
1 1 1 1
2 1 2 NaN
3 1 3 3
4 1 4 5
#Formula syntax. Note the index for hour 2 has been silently dropped.
aggregate(val ~ hour + day,data=a,mean,na.rm=T)
hour day val
1 1 1 1
2 3 1 3
3 4 1 5
TRY:
SELECT EXTRACT(YEAR FROM (STR_TO_DATE(subdateshow, '%d/%m/%Y')));
If using webdriverJs (node.js),
driver.findElement(webdriver.By.name('btnCalculate')).click().then(function() {
driver.sleep(5000);
});
The code above makes browser wait for 5 seconds after clicking the button.
If you use an appropriate class or library, they will do the escaping for you. Many XML issues are caused by string concatenation.
There are only five:
" "
' '
< <
> >
& &
Escaping characters depends on where the special character is used.
The examples can be validated at the W3C Markup Validation Service.
The safe way is to escape all five characters in text. However, the three characters "
, '
and >
needn't be escaped in text:
<?xml version="1.0"?>
<valid>"'></valid>
The safe way is to escape all five characters in attributes. However, the >
character needn't be escaped in attributes:
<?xml version="1.0"?>
<valid attribute=">"/>
The '
character needn't be escaped in attributes if the quotes are "
:
<?xml version="1.0"?>
<valid attribute="'"/>
Likewise, the "
needn't be escaped in attributes if the quotes are '
:
<?xml version="1.0"?>
<valid attribute='"'/>
All five special characters must not be escaped in comments:
<?xml version="1.0"?>
<valid>
<!-- "'<>& -->
</valid>
All five special characters must not be escaped in CDATA sections:
<?xml version="1.0"?>
<valid>
<![CDATA["'<>&]]>
</valid>
All five special characters must not be escaped in XML processing instructions:
<?xml version="1.0"?>
<?process <"'&> ?>
<valid/>
HTML has its own set of escape codes which cover a lot more characters.
This will import and display a .jpg
image in Jupyter (tested with Python 2.7 in Anaconda environment)
from IPython.display import display
from PIL import Image
path="/path/to/image.jpg"
display(Image.open(path))
in Anaconda this is done by typing
conda install pillow
Use the following library:
import javax.swing.JOptionPane;
Input at the top of the code-line. You must only add this, because the other things is done correctly!
var results = (medicineInfo.OrderBy(x=>x.id)_x000D_
.Skip((pages -1) * 2)_x000D_
.Take(2));
_x000D_
File file = new File("Path");
FileReader reader = new FileReader(file);
while((ch=reader.read())!=-1)
{
System.out.print((char)ch);
}
This worked for me
You can use the nose-ittr plugin (pip install nose-ittr
).
It's very easy to integrate with existing tests, and minimal changes (if any) are required. It also supports the nose multiprocessing plugin.
Note that you can also have a customize setup
function per test.
@ittr(number=[1, 2, 3, 4])
def test_even(self):
assert_equal(self.number % 2, 0)
It is also possible to pass nosetest
parameters like with their built-in plugin attrib
. This way you can run only a specific test with specific parameter:
nosetest -a number=2
Crude, but it works on our system:
<div class="block-share spread-share p-t-md">
<a href="http://www.facebook.com/share.php?u=http://www.voteleavetakecontrol.org/our_affiliates&title=Farmers+for+Britain+have+made+the+sensible+decision+to+Vote+Leave.+Be+part+of+a+better+future+for+us+all.+Please+share!"
target="_blank">
<button class="btn btn-social btn-facebook">
<span class="icon icon-facebook">
</span>
Share on Facebook
</button>
</a>
<a href="https://www.facebook.com/FarmersForBritain" target="_blank">
<button class="btn btn-social btn-facebook">
<span class="icon icon-facebook">
</span>
Like on Facebook
</button>
</a>
</div>
LOESS is a very good approach, as Dirk said.
Another option is using Bezier splines, which may in some cases work better than LOESS if you don't have many data points.
Here you'll find an example: http://rosettacode.org/wiki/Cubic_bezier_curves#R
# x, y: the x and y coordinates of the hull points
# n: the number of points in the curve.
bezierCurve <- function(x, y, n=10)
{
outx <- NULL
outy <- NULL
i <- 1
for (t in seq(0, 1, length.out=n))
{
b <- bez(x, y, t)
outx[i] <- b$x
outy[i] <- b$y
i <- i+1
}
return (list(x=outx, y=outy))
}
bez <- function(x, y, t)
{
outx <- 0
outy <- 0
n <- length(x)-1
for (i in 0:n)
{
outx <- outx + choose(n, i)*((1-t)^(n-i))*t^i*x[i+1]
outy <- outy + choose(n, i)*((1-t)^(n-i))*t^i*y[i+1]
}
return (list(x=outx, y=outy))
}
# Example usage
x <- c(4,6,4,5,6,7)
y <- 1:6
plot(x, y, "o", pch=20)
points(bezierCurve(x,y,20), type="l", col="red")
Why not just add "min-width" to your css-class?
If you are using maven , Go to maven dependencies in your project structure then run lombok jar as java project it will install it then exit and start eclipse
From what I've read, the need for constexpr comes from an issue in metaprogramming. Trait classes may have constants represented as functions, think: numeric_limits::max(). With constexpr, those types of functions can be used in metaprogramming, or as array bounds, etc etc.
Another example off of the top of my head would be that for class interfaces, you may want derived types define their own constants for some operation.
Edit:
After poking around on SO, it looks like others have come up with some examples of what might be possible with constexprs.
If you know the actual enum labels correlated to their values, you can use containers and C++17's std::string_view
to quickly access values and their string representations with the [
]
operator while tracking it yourself. std::string_view
will only allocate memory when created. They can also be designated with static constexpr
if you want them available at run-time for more performance savings. This little console app should be fairly fast.
#include <iostream>
#include <string_view>
#include <tuple>
int main() {
enum class Weekdays { //default behavior starts at 0 and iterates by 1 per entry
Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
};
static constexpr std::string_view Monday = "Monday";
static constexpr std::string_view Tuesday = "Tuesday";
static constexpr std::string_view Wednesday = "Wednesday";
static constexpr std::string_view Thursday = "Thursday";
static constexpr std::string_view Friday = "Friday";
static constexpr std::string_view Saturday = "Saturday";
static constexpr std::string_view Sunday = "Sunday";
static constexpr std::string_view opener = "enum[";
static constexpr std::string_view closer = "] is ";
static constexpr std::string_view semi = ":";
std::pair<Weekdays, std::string_view> Weekdays_List[] = {
std::make_pair(Weekdays::Monday, Monday),
std::make_pair(Weekdays::Tuesday, Tuesday),
std::make_pair(Weekdays::Wednesday, Wednesday),
std::make_pair(Weekdays::Thursday, Thursday),
std::make_pair(Weekdays::Friday, Friday),
std::make_pair(Weekdays::Saturday, Saturday),
std::make_pair(Weekdays::Sunday, Sunday)
};
for (int i=0;i<sizeof(Weekdays_List)/sizeof(Weekdays_List[0]);i++) {
std::cout<<opener<<i<<closer<<Weekdays_List[(int)i].second<<semi\
<<(int)Weekdays_List[(int)i].first<<std::endl;
}
return 0;
}
Output:
enum[0] is Monday:0
enum[1] is Tuesday:1
enum[2] is Wednesday:2
enum[3] is Thursday:3
enum[4] is Friday:4
enum[5] is Saturday:5
enum[6] is Sunday:6
You could also do something like:
String str = "a + b - c * d / e < f > g >= h <= i == j";
String[] arr = str.split("(?<=\\G(\\w+(?!\\w+)|==|<=|>=|\\+|/|\\*|-|(<|>)(?!=)))\\s*");
It handles white spaces and words of variable length and produces the array:
[a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j]
Just like you said
select * from tbl where statusid is null
or
select * from tbl where statusid is not null
If your statusid is not null, then it will be selected just fine when you have an actual value, no need for any "if" logic if that is what you were thinking
select * from tbl where statusid = 123 -- the record(s) returned will not have null statusid
if you want to select where it is null or a value, try
select * from tbl where statusid = 123 or statusid is null
You could try with this for mime type
$image = getimagesize($_FILES['image']['tmp_name']);
$image['mime']
will return the mime type.
This function doesn't require GD library. You can find the documentation here.
This returns the mime type of the image.
Some people use the $_FILES["file"]["type"]
but it's not reliable as been given by the browser and not by PHP.
You can use pathinfo()
as ThiefMaster suggested to retrieve the image extension.
First make sure that the image is being uploaded successfully while in development before performing any operations with the image.
For those who have a custom jQuery UI build (bower for ex.), add the effects core located in ..\jquery-ui\ui\effect.js
.
You can make a menu for each fragment, and a global variable that mark which fragment is in use now. and check the value of the variable in onCreateOptionsMenu and inflate the correct menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (fragment_it == 6) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.custom_actionbar, menu);
}
}
You have to construct a new string out of a byte array. The first element in your byteArray
should be 0x63
. If you want to add any more letters, make the byteArray
longer and add them to the next indices.
byte[] byteArray = new byte[1];
byteArray[0] = 0x63;
try {
System.out.println("string " + new String(byteArray, "US-ASCII"));
} catch (UnsupportedEncodingException e) {
// TODO: Handle exception.
e.printStackTrace();
}
Note that specifying the encoding will eventually throw an UnsupportedEncodingException
and you must handle that accordingly.
A boolean in SQL is a bit field. This means either 1 or 0. The correct syntax is:
select * from users where active = 1 /* All Active Users */
or
select * from users where active = 0 /* All Inactive Users */
Like you said in your title, fgetcsv is the way to go. It's pretty darn easy to use.
$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
print_r($line);
}
fclose($file);
You'll want to put more error checking in there in case fopen()
fails, but this works to read a CSV file line by line and parse the line into an array.
How about another, simpler approach:
require 'fileutils'
FileUtils.cmp(file1, file2)
Something like this..
RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.widget43);
// ListView listView = (ListView) findViewById(R.id.ListView01);
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// View footer = inflater.inflate(R.layout.footer, null);
View footer = LayoutInflater.from(this).inflate(R.layout.footer,
null);
final RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1);
footer.setLayoutParams(layoutParams);
You can now toggle column selection mode, which changes mouse gestures and arrow keys, via:
"editor.action.toggleColumnSelection"
Note: There is a "Column Selection" panel in the status bar after activation, which you can press to disable it again.
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
There's no single method that will do what you want. You will need to make a clone method available for the class in your array. Then, if LINQ is an option:
Foo[] newArray = oldArray.Skip(3).Take(5).Select(item => item.Clone()).ToArray();
class Foo
{
public Foo Clone()
{
return (Foo)MemberwiseClone();
}
}
sudo nginx -t
should test all files and return errors and warnings locations
use an enum type to indicate your ViewModel's State
public enum ViewModeType
{
Default,
Busy
//etc.
}
then in your ViewModels Base class use a property
public ViewModeType ViewMode
{
get { return this.viewMode; }
set
{
if (this.viewMode != value)
{
this.viewMode = value;
//You should notify property changed here
}
}
}
and in view trigger the ViewMode and if it is busy show busyindicator:
<Trigger Property="ViewMode" Value="Busy">
<!-- Show BusyIndicator -->
</Trigger>
1)install "lite server" and then try below command :
npm run lite
If you're using AngularJS and your jQuery click event is INSIDE THE CONTROLLER, it will get disturbed by the Angular's framework itself and fire twice. To solve this, move it out of the controller and do the following:
// Make sure you're using $(document), or else it won't fire.
$(document).on("click", "#myTemplateId #myButtonId", function () {
console.log("#myButtonId is fired!");
// Do something else.
});
angular.module("myModuleName")
.controller("myController", bla bla bla)
I had a similar problem just now. However, this had nothing to do with modifying the php.ini
file. It was from a for loop. If you are having nested for
loops, make sure you are using the iterator properly. In my case, I was iterating the outer iterator from my inner iterator.
You can simplify things quite a bit by creating a class that derives from WebClient, overriding its GetWebRequest method and setting a CookieContainer object on it. If you always set the same CookieContainer instance, then cookie management will be handled automatically for you.
But the only way to get at the HttpWebRequest before it is sent is to inherit from WebClient and override that method.
public class CookieAwareWebClient : WebClient
{
private CookieContainer cookie = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = cookie;
}
return request;
}
}
var client = new CookieAwareWebClient();
client.BaseAddress = @"https://www.site.com/any/base/url/";
var loginData = new NameValueCollection();
loginData.Add("login", "YourLogin");
loginData.Add("password", "YourPassword");
client.UploadValues("login.php", "POST", loginData);
//Now you are logged in and can request pages
string htmlSource = client.DownloadString("index.php");
The error could be improved, but the problem with your first version is you have a member variable, delegate
, that does not have a default value. All variables in Swift must always have a value. That means that you have to set it up in an initializer which you do not have or you could provide it a default value in-line.
When you make it optional, you allow it to be nil
by default, removing the need to explicitly give it a value or initialize it.
SendRedirect()
will search the content between the servers. it is slow because it has to intimate the browser by sending the URL of the content. then browser will create a new request for the content within the same server or in another one.
RquestDispatcher
is for searching the content within the server i think. its the server side process and it is faster compare to the SendRedirect()
method. but the thing is that it will not intimate the browser in which server it is searching the required date or content, neither it will not ask the browser to change the URL in URL tab. so it causes little inconvenience to the user.
Here is a function I came up with
function getElementsById(elementID){
var elementCollection = new Array();
var allElements = document.getElementsByTagName("*");
for(i = 0; i < allElements.length; i++){
if(allElements[i].id == elementID)
elementCollection.push(allElements[i]);
}
return elementCollection;
}
Apparently there is a convention supported by prototype, and probably other major JavaScript libraries.
However, I have come to discover that dollar sign function has become the more-or-less de facto shortcut to document.getElementById(). Let’s face it, we all use document.getElementById() a lot. Not only does it take time to type, but it adds bytes to your code as well.
here is the function from prototype:
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length; i++)
elements.push($(arguments[i]));
return elements;
}
if (Object.isString(element))
element = document.getElementById(element);
return Element.extend(element);
}
Thanks to ZipArchive creates invalid ZIP file, I got:
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
var demoFile = archive.CreateEntry("foo.txt");
using (var entryStream = demoFile.Open())
using (var streamWriter = new StreamWriter(entryStream))
{
streamWriter.Write("Bar!");
}
}
using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
{
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(fileStream);
}
}
That indicated we need to call Dispose
on ZipArchive
before we can use it, which as Amir suggests is likely because it writes final bytes like checksum to the archive that makes it complete. But in order not close the stream so we can re-use it after you need to pass true
as the third parameter to ZipArchive
.
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(response);// response will be the json String
YourPojo emp = gson.fromJson(object, YourPojo.class);
In Xcode-11.2.1
You might be see different pattern for uploading IPA
Steps:-
i) Add your apple developer id in xcode preference -> account
ii)Clean Build Folder :-
iii) Archive
iv) Tap on Distribute App
v) Choose Ad-hoc to distribute on designated device
6)Tricky part -> User can download app from company's website URL. Many of us might get stuck and start creating website url to upload ipa, which is not required. Simply write google website url with https. :)
7)Click on export and you get ipa.
8)Visit https://www.diawi.com/ & drag and drop ipa you have downloaded. & share the link to your client/user who want to test :)
try this
select * from <tablename> where 1=2
...............................................
The best place to understand the difference is at the official documentation on values / values_list. It has many useful examples and explains it very clearly. The django docs are very user freindly.
Here's a short snippet to keep SO reviewers happy:
Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.
And read the section which follows it:
This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over.
Well a fix for you could be to put it on the UpdatedDate field and have a trigger that updates the AddedDate field with the UpdatedDate value only if AddedDate is null.
The way i do it is:
var obj = new Object();
obj.name = "Raj";
obj.age = 32;
obj.married = false;
var jsonString= JSON.stringify(obj);
I guess this way can reduce chances for errors.
if you hit the "back" button it usually tends to stick, what you can do is when the form is submitted clear the element then before it goes to the next page but after doing with the element what you need to.
$('#shares').keyup(function(){
payment = 0;
calcTotal();
gtotal = ($('#shares').val() * 1) + payment;
gtotal = gtotal.toFixed(2);
$('#shares').val('');
$("p.total").html("Total Payment: <strong>" + gtotal + "</strong>");
});
I faced same issue & it resolved by
ENTRYPOINT ["sh", "/docker-entrypoint.sh"]
For the Dockerfile in the original question it should be like:
ENTRYPOINT ["sh", "/usr/src/app/docker-entrypoint.sh"]
I found this answer on another site but it definitely worked for me so I thought I would share it.
In Windows Explorer: Right Click on the folder OfficeSoftwareProtection Platform from C:\Program Files\Common Files\Microsoft Shared and Microsoft from C:\Program data(this is a hidden folder) Properties > Security > Edit > Add > Type Network Service > OK > Check the Full control box > Apply and OK.
In Registry Editor (regedit.exe): Go to HKEY_CLASSES_ROOT\AppID registry >Right Click on the folder > Permissions > Add > Type = NETWORK SERVICE > OK > Check Full Control > Apply > OK
I found this response here::: https://social.technet.microsoft.com/Forums/windows/en-US/5dda9b0b-636f-4f2f-8e50-ad05e98ab22d/error-1920-service-office-software-protection-platform-osppsvc-failed-to-start-verify-that-you?forum=officesetupdeployprevious
Which was originally a method discovered by Jennifer Zhan
You can also use Underscore.js which is basically a swiss-knife library to manipulate collections. Using _.filter
, _.pluck
, _.reduce
you can do SQL-like queries.
var data = [{"x": 2, "y": 0}, {"x": 3, "y": 1}, {"x": 4, "y": 1}];
var posData = _.filter(data, function(elt) { return elt.y > 0; });
// [{"x": 3, "y": 1}, {"x": 4, "y": 1}]
var values = _.pluck(posData, "x");
// [3, 4]
var sum = _.reduce(values, function(a, b) { return a+b; });
// 7
Underscore.js works both client-side and server-side and is a notable library.
You can also use Lo-Dash which is a fork of Underscore.js with better performances.
Something worth noting is that INSERT IGNORE will still increment the primary key whether the statement was a success or not just like a normal INSERT would.
This will cause gaps in your primary keys that might make a programmer mentally unstable. Or if your application is poorly designed and depends on perfect incremental primary keys, it might become a headache.
Look into innodb_autoinc_lock_mode = 0
(server setting, and comes with a slight performance hit), or use a SELECT first to make sure your query will not fail (which also comes with a performance hit and extra code).
Even after toggling it did not work. I closed and restarted the browser after adding the postman plugin, logged into the site to generate cookies afresh and then it worked for me.
You should declare it with declarations array(meta property) of @NgModule
as shown below (RC5 and later
),
import {CoursesComponent} from './courses.component';
@NgModule({
imports: [ BrowserModule],
declarations: [ AppComponent,CoursesComponent], //<----here
providers: [],
bootstrap: [ AppComponent ]
})
For completion's sake, here's the snippet that creates the transport client using proper static method provided by InetSocketTransportAddress
:
Client esClient = TransportClient.builder()
.settings(settings)
.build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("143.79.236.xxx"), 9300));
If you're familiar with other popular services:
Google Compute Engine -> AWS EC2
Google App Engine -> Heroku or AWS Elastic Beanstalk
Google Cloud Functions -> AWS Lambda Functions
From GC Performance Tuning training documents of Oracle:
-Xmn[size]: Size of young generation heap space.
Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.
In short, it sets the NewSize and MaxNewSize values of New generation to the same value.
The default shell (/bin/sh
) under Ubuntu points to dash
, not bash
.
me@pc:~$ readlink -f $(which sh)
/bin/dash
So if you chmod +x your_script_file.sh
and then run it with ./your_script_file.sh
, or if you run it with bash your_script_file.sh
, it should work fine.
Running it with sh your_script_file.sh
will not work because the hashbang line will be ignored and the script will be interpreted by dash
, which does not support that string substitution syntax.
Encountered the same error in different use case.
Use Case: In chrome when tried to call Spring REST end point in angular.
Solution: Add @CrossOrigin("*") annotation on top of respective Controller Class.
Use target="_top"
attribute in anchor tag that will really work.
If someone doesn't want to override default Control Template then here is the solution.
You can create DataTemplate for button which can have TextBlock and then you can write Property trigger on IsMouseOver property to disable mouse over effect. Height of TextBlock and Button should be same.
<Button Background="Black" Margin="0" Padding="0" BorderThickness="0" Cursor="Hand" Height="20">
<Button.ContentTemplate>
<DataTemplate>
<TextBlock Text="GO" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" TextDecorations="Underline" Margin="0" Padding="0" Height="20">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger Property ="IsMouseOver" Value="True">
<Setter Property= "Background" Value="Black"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</Button.ContentTemplate>
</Button>
I went back to jquery-2.2.4.min.js and it works.
If I understood you right, you want to copy $var
in a file (if it's a string).
echo $var > $destdir
You need to use to_timestamp()
to convert your string to a proper timestamp
value:
to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
If your column is of type DATE
(which also supports seconds), you need to use to_date()
to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
To get this into a where
condition use the following:
select *
from TableA
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')
You never need to use to_timestamp()
on a column that is of type timestamp
.
You can try using:
select trunc(sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) as days from dual
Run java
with -d64
or -d32
specified, it will give you an error message if it doesn't support 64-bit or 32-bit respectively. Your JVM may support both.
Try like this
$("#drop").change(function () {
var end = this.value;
var firstDropVal = $('#pick').val();
});
l=[['A', 1], ['B', 2], ['C', 3]]
d={}
for i,j in l:
d.setdefault(i,j)
print(d)
Regex won't help much. First of all, you will want to take into account the operators precedence, and second, you need to work with parentheses which is impossible with regex.
Depending on what exactly kind of expression you need to parse, you may try either Python AST or (more likely) pyparsing. But, first of all, I'd recommend to read something about syntax analysis in general and the Shunting yard algorithm in particular.
And fight the temptation of using eval
, that's not safe.
I was reading path from a properties file and didn't mention there was a space in the end. Make sure you don't have one.
I was facing two issues Issue 1: all fields were coming one after other and Issue 2 white space at the bottom of the page when used to print from popup.
I Resolved this by
making display none to all body * elements most of them go for visibility hidden which creates space so avoid visibility hidden
@media print {
body * {
display:none;
width:auto;
height:auto;
margin:0px;padding:0px;
}
#printSection, #printSection * {
display:inline-block!important;
}
#printSection {
position:absolute;
left:0;
top:0;
margin:0px;
page-break-before: none;
page-break-after: none;
page-break-inside: avoid;
}
#printSection .form-group{
width:100%!important;
float:left!important;
page-break-after: avoid;
}
#printSection label{
float:left!important;
width:200px!important;
display:inline-block!important;
}
#printSection .form-control.search-input{
float:left!important;
width:200px!important;
display: inline-block!important;
}
}
I also had this problem. It was caused by the development server not deleting the django session after a debug abort in Aptana, with subsequent database deletion. (Meaning the id of a non-existent database record was still present in the session the next time the development server started)
To resolve this during development, I used
request.session.flush()
OK, the right answer definitely has to do something with the CPU cache. But to use the cache argument can be quite difficult, especially without data.
There are many answers, that led to a lot of discussion, but let's face it: Cache issues can be very complex and are not one dimensional. They depend heavily on the size of the data, so my question was unfair: It turned out to be at a very interesting point in the cache graph.
@Mysticial's answer convinced a lot of people (including me), probably because it was the only one that seemed to rely on facts, but it was only one "data point" of the truth.
That's why I combined his test (using a continuous vs. separate allocation) and @James' Answer's advice.
The graphs below shows, that most of the answers and especially the majority of comments to the question and answers can be considered completely wrong or true depending on the exact scenario and parameters used.
Note that my initial question was at n = 100.000. This point (by accident) exhibits special behavior:
It possesses the greatest discrepancy between the one and two loop'ed version (almost a factor of three)
It is the only point, where one-loop (namely with continuous allocation) beats the two-loop version. (This made Mysticial's answer possible, at all.)
The result using initialized data:
The result using uninitialized data (this is what Mysticial tested):
And this is a hard-to-explain one: Initialized data, that is allocated once and reused for every following test case of different vector size:
Every low-level performance related question on Stack Overflow should be required to provide MFLOPS information for the whole range of cache relevant data sizes! It's a waste of everybody's time to think of answers and especially discuss them with others without this information.
Case 1: All socks are identical (this is what I do in real life by the way).
Pick any two of them to make a pair. Constant time.
Case 2: There are a constant number of combinations (ownership, color, size, texture, etc.).
Use radix sort. This is only linear time since comparison is not required.
Case 3: The number of combinations is not known in advance (general case).
We have to do comparison to check whether two socks come in pair. Pick one of the O(n log n)
comparison-based sorting algorithms.
However in real life when the number of socks is relatively small (constant), these theoretically optimal algorithms wouldn't work well. It might take even more time than sequential search, which theoretically requires quadratic time.
Although stretching to elements with position: absolute
is not possible, there are often solutions where you can avoid the absolute positioning while obtaining the same effect. Look at this fiddle that solves the problem in your particular case http://jsfiddle.net/gS9q7/
The trick is to reverse element order by floating both elements, the first to the right, the second to the left, so the second appears first.
.child1 {
width: calc(100% - 160px);
float: right;
}
.child2 {
width: 145px;
float: left;
}
Finally, add a clearfix to the parent and you're done (see the fiddle for the complete solution).
Generally, as long as the element with absolute position is positioned at the top of the parent element, chances are good that you find a workaround by floating the element.
By default, Valgrind writes its output to stderr. So you need to do something like:
valgrind a.out > log.txt 2>&1
Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).
If you realy need to restart your app, you could write a separate app the start it...
This page provides many different examples for different scenarios:
This is a basic example with comments. The upload
function is what you are looking for:
// Select your input type file and store it in a variable
const input = document.getElementById('fileinput');
// This will upload the file after having read it
const upload = (file) => {
fetch('http://www.example.net', { // Your POST endpoint
method: 'POST',
headers: {
// Content-Type may need to be completely **omitted**
// or you may need something
"Content-Type": "You will perhaps need to define a content-type here"
},
body: file // This is your file object
}).then(
response => response.json() // if the response is a JSON object
).then(
success => console.log(success) // Handle the success response object
).catch(
error => console.log(error) // Handle the error response object
);
};
// Event handler executed when a file is selected
const onSelectFile = () => upload(input.files[0]);
// Add a listener on your input
// It will be triggered when a file will be selected
input.addEventListener('change', onSelectFile, false);
With Lodash you can create a template and you can do that following way:
<div class="container">
<div class="row justify-content-center">
<div class="col-12">
<table id="tblEntAttributes" class="table">
<tbody>
<tr>
<td>
chkboxId
</td>
<td>
chkboxValue
</td>
<td>
displayName
</td>
<td>
logicalName
</td>
<td>
dataType
</td>
</tr>
</tbody>
</table>
<button class="btn btn-primary" id="test">appendTo</button>
</div>
</div>
</div>
And here goes the javascript:
var count = 1;
window.addEventListener('load', function () {
var compiledRow = _.template("<tr><td><input type=\"checkbox\" id=\"<%= chkboxId %>\" value=\"<%= chkboxValue %>\"></td><td><%= displayName %></td><td><%= logicalName %></td><td><%= dataType %></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td></tr>");
document.getElementById('test').addEventListener('click', function (e) {
var ajaxData = { 'chkboxId': 'chkboxId-' + count, 'chkboxValue': 'chkboxValue-' + count, 'displayName': 'displayName-' + count, 'logicalName': 'logicalName-' + count, 'dataType': 'dataType-' + count };
var tableRowData = compiledRow(ajaxData);
$("#tblEntAttributes tbody").append(tableRowData);
count++;
});
});
Here it is in jsbin
I was having this issue too with SQL Server 2017.
I'm on the same network as the server via VPN and can ping it. After being frustrated that no authentication method would work - I set up an SSH server on the SQL server - and I was able to connect normally. This confirmed the correct port wasn't being hit for some reason. I even created a new user accounts, domain accounts, firewall checks on both ends, etc...
The solution for me was: 1. Set Connection to strictly use TCP/IP on SSMS 2. Use a custom string to point to the default port (ex: Data Source=192.168.168.166,1433;)
All the other comments above haven't worked so far. It looks like it was mandatory to include the port (even though its default).
To refresh the component at regular intervals I found this the best method. In the ngOnInit method setTimeOut function
ngOnInit(): void {
setTimeout(() => { this.ngOnInit() }, 1000 * 10)
}
//10 is the number of seconds
Check out termsql. https://gitorious.org/termsql https://gitorious.org/termsql/pages/Home
It converts text to SQL on the command line. (CSV is just text)
Example:
cat textfile | termsql -o sqlite.db
By default the delimiter is whitespace, so to make it work with CSV that is using commata, you'd do it like this:
cat textfile | termsql -d ',' -o sqlite.db
alternatively you can do this:
termsql -i textfile -d ',' -o sqlite.db
By default it will generate column names "COL0", "COL1", if you want it to use the first row for the columns names you do this:
termsql -i textfile -d ',' -1 -o sqlite.db
If you want to set custom column names you do this:
termsql -i textfile -d ',' -c 'id,name,age,color' -o sqlite.db
To add to the response from @Anish, if you are having issues with not seeing the text when exporting the SVG to an image, you can create a recursive function to loop through the children of the SVGDocument, try to cast it to a SvgText if possible (add your own error checking) and set the font family and style.
foreach(var child in svgDocument.Children)
{
SetFont(child);
}
public void SetFont(SvgElement element)
{
foreach(var child in element.Children)
{
SetFont(child); //Call this function again with the child, this will loop
//until the element has no more children
}
try
{
var svgText = (SvgText)parent; //try to cast the element as a SvgText
//if it succeeds you can modify the font
svgText.Font = new Font("Arial", 12.0f);
svgText.FontSize = new SvgUnit(12.0f);
}
catch
{
}
}
Let me know if there are questions.
The print statement will output an object to the user. A return statement will allow assigning the dictionary to a variable once the function is finished.
>>> def foo():
... print "Hello, world!"
...
>>> a = foo()
Hello, world!
>>> a
>>> def foo():
... return "Hello, world!"
...
>>> a = foo()
>>> a
'Hello, world!'
Or in the context of returning a dictionary:
>>> def foo():
... print {'a' : 1, 'b' : 2}
...
>>> a = foo()
{'a': 1, 'b': 2}
>>> a
>>> def foo():
... return {'a' : 1, 'b' : 2}
...
>>> a = foo()
>>> a
{'a': 1, 'b': 2}
(The statements where nothing is printed out after a line is executed means the last statement returned None)
The Apache project has a library called POI which can be used to generate MS Office files. It is a Java library but the advantage is that it can run on Linux with no trouble. This library has its limitations but it may do the job for you, and it's probably simpler to use than trying to run Word.
Another option would be OpenOffice but I can't exactly recommend it since I've never used it.
You can use MySQL Table Data Import Wizard
Diff has an option -r
which is meant to do just that.
diff -r dir1 dir2
CURL-less method with PHP5:
$url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
See the PHP manual for more information on the method and how to add headers, for example:
When working with bootsrap usually face three main problems:
To solve first two problems download this small plugin https://github.com/codekipple/conformity
The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns
<style>
[class*=col-] {position: relative}
.row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
.row-centered {text-align:center}
.row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top}
</style>
<script src="assets/conformity/conformity.js"></script>
<script>
$(document).ready(function () {
$('.row-conformity > [class*=col-]').conformity();
$(window).on('resize', function() {
$('.row-conformity > [class*=col-]').conformity();
});
});
</script>
<div class="row row-conformity">
<div class="col-sm-3">
I<br>create<br>highest<br>column
</div>
<div class="col-sm-3">
<div class="to-bottom">
I am on the bottom
</div>
</div>
</div>
<div class="row row-conformity">
<div class="col-sm-4">We all have equal height</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
</div>
<div class="row row-centered">
<div class="col-sm-3">...</div>
<div class="col-sm-4">...</div>
</div>
<div class="row row-conformity row-centered">
...
</div>
First off, you need to get a MemberInfo
object that represents that property. You will need to do some form of reflection:
MemberInfo property = typeof(Class1).GetProperty("Name");
(I'm using "old-style" reflection, but you can also use an expression tree if you have access to the type at compile-time)
Then you can fetch the attribute and obtain the value of the DisplayName
property:
var attribute = property.GetCustomAttributes(typeof(DisplayNameAttribute), true)
.Cast<DisplayNameAttribute>().Single();
string displayName = attribute.DisplayName;
() parentheses are required typo error
The easiest way to do this would be to use a filter.
You can either filter for any cells in column A that don't have a "-" and copy / paste, or (my more preferred method) filter for all cells that do have a "-" and then select all and delete - Once you remove the filter, you're left with what you need.
Hope this helps.
There is Array.filter()
:
var numbers = [1, 2, 3, 4, 5];
var filtered = numbers.filter(function(x) { return x > 3; });
// As a JavaScript 1.8 expression closure
filtered = numbers.filter(function(x) x > 3);
Note that Array.filter()
is not standard ECMAScript, and it does not appear in ECMAScript specs older than ES5 (thanks Yi Jiang and jAndy). As such, it may not be supported by other ECMAScript dialects like JScript (on MSIE).
Nov 2020 Update: Array.filter is now supported across all major browsers.
uses-permission android:name="android.permission.SEND_SMS"/>
Prem
at this thread ) and replace the below phone_Number by an actual number, it will work:startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", "phone_Number", null)));
!important
, and give the selector a higher specificity (adding an additional tag, id or class to the selector)Some examples with a higher specificity (first is highest/overrides, third is lowest):
table td {height: 50px !important;}
.myTable td {height: 50px !important;}
#myTable td {height: 50px !important;}
Or add the same selector after the existing one:
td {height: 50px !important;}
It's almost never a good idea to use !important
. This is bad engineering by the creators of the WordPress template. In viral fashion, it forces users of the template to add their own !important
modifiers to override it, and it limits the options for overriding it via JavaScript.
But, it's useful to know how to override it, if you sometimes have to.
.disabledLink.disabled {pointer-events:none;}
That should do it hope I helped!
If you use yum search you can find the python dev package for your version of python.
For me I was using python 3.5. I ran the following
yum search python | grep devel
Which returned the following
I was then able to install the correct package for my version of python with the following cmd.
sudo yum install python35u-devel.x86_64
This works on centos for ubuntu or debian you would need to use apt-get
In my case, I had the following structure of a project:
When I was running the test, I kept receiving problems with auro-wiring both facade and kafka attributes - error came back with information about missing instances, even though the test and the API classes reside in the very same package. Apparently those were not scanned.
What actually helped was adding @Import annotation bringing the missing classes to Spring classpath and making them being instantiated.
This may not be the prettiest, but if you don't want to use the MessageBoxManager, (which is awesome):
public static DialogResult DialogBox(string title, string promptText, ref string value, string button1 = "OK", string button2 = "Cancel", string button3 = null)
{
Form form = new Form();
Label label = new Label();
TextBox textBox = new TextBox();
Button button_1 = new Button();
Button button_2 = new Button();
Button button_3 = new Button();
int buttonStartPos = 228; //Standard two button position
if (button3 != null)
buttonStartPos = 228 - 81;
else
{
button_3.Visible = false;
button_3.Enabled = false;
}
form.Text = title;
// Label
label.Text = promptText;
label.SetBounds(9, 20, 372, 13);
label.Font = new Font("Microsoft Tai Le", 10, FontStyle.Regular);
// TextBox
if (value == null)
{
}
else
{
textBox.Text = value;
textBox.SetBounds(12, 36, 372, 20);
textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
}
button_1.Text = button1;
button_2.Text = button2;
button_3.Text = button3 ?? string.Empty;
button_1.DialogResult = DialogResult.OK;
button_2.DialogResult = DialogResult.Cancel;
button_3.DialogResult = DialogResult.Yes;
button_1.SetBounds(buttonStartPos, 72, 75, 23);
button_2.SetBounds(buttonStartPos + 81, 72, 75, 23);
button_3.SetBounds(buttonStartPos + (2 * 81), 72, 75, 23);
label.AutoSize = true;
button_1.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
button_2.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
button_3.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
form.ClientSize = new Size(396, 107);
form.Controls.AddRange(new Control[] { label, button_1, button_2 });
if (button3 != null)
form.Controls.Add(button_3);
if (value != null)
form.Controls.Add(textBox);
form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
form.MinimizeBox = false;
form.MaximizeBox = false;
form.AcceptButton = button_1;
form.CancelButton = button_2;
DialogResult dialogResult = form.ShowDialog();
value = textBox.Text;
return dialogResult;
}
Where is your problem??
For the stored procedure, just create:
CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
SELECT * -- I would *strongly* recommend specifying the columns EXPLICITLY
FROM dbo.Emp
WHERE ID = @EmpID
That's all there is.
From your ASP.NET application, just create a SqlConnection
and a SqlCommand
(don't forget to set the CommandType = CommandType.StoredProcedure
)
DataTable tblEmployees = new DataTable();
using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
_cmd.Parameters["@EmpID"].Value = 42;
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_dap.Fill(tblEmployees);
}
YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();
and then fill e.g. a DataTable
with that data and bind it to e.g. a GridView.
The response provided by Ranveer (second answer above) absolutely does NOT work.
He says to use col-xx-offset-#
, but that is not how offsets are used.
If you wasted your time trying to use col-xx-offset-#
, as I did based on his answer, the solution is to use offset-xx-#
.
The following function will delete the input character one by one till the input field is empty using PromiseWhile
driver.clearKeys = function(element, value){
return element.getAttribute('value').then(function(val) {
if (val.length > 0) {
return new Promise(function(resolve, reject) {
var len;
len = val.length;
return promiseWhile(function() {
return 0 < len;
}, function() {
return new Promise(function(resolve, reject) {
len--;
return element.sendKeys(webdriver.Key.BACK_SPACE).then(function() {
return resolve(true);
});
});
}).then(function() {
return resolve(true);
});
});
}
curl_getinfo
— Get information regarding a specific transfer
Check curl_getinfo
<?php
// Create a curl handle
$ch = curl_init('http://www.yahoo.com/');
// Execute
curl_exec($ch);
// Check if any error occurred
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
}
// Close handle
curl_close($ch);
The WHERE
clause is misplaced, it has to follow the table references and JOIN operations.
Something like this:
FROM tartikel p1
JOIN tartikelpict p2
ON p1.kArtikel = p2.kArtikel
AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC
EDIT (three plus years later)
The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"
As to a question about writing a condition that checks a date range of "last 7 days"...
That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.
To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".
If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT
SELECT DATE(NOW()) + INTERVAL -1 DAY
and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:
WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY
For a DATETIME or TIMESTAMP column, we can use >=
and <
inequality comparisons to specify a range
WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
AND datetimecol < DATE(NOW()) + INTERVAL 0 DAY
For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...
WHERE datetimecol >= NOW() + INTERVAL -7 DAY
AND datetimecol < NOW() + INTERVAL 0 DAY
the last seven complete days, not including today
WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
AND datetimecol < DATE(NOW()) + INTERVAL 0 DAY
or past six complete days plus so far today ...
WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
AND datetimecol < NOW() + INTERVAL 0 DAY
I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.
SET @clock = '2017-11-17 11:47:47' ;
SELECT DATE(@clock)
, DATE(@clock) + INTERVAL -7 DAY
, @clock + INTERVAL -6 DAY
Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.
(Some developers prefer to use the DATE_ADD
and DATE_SUB
functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR
syntax.
And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,
Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is
WHERE datetimecol >= '2017-11-10 00:00'
AND datetimecol < '2017-11-17 00:00'
And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...
WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
AND datetimecol < '2017-11-17 00:00' + INTERVAL 0 SECOND
The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy'
, m/d/yyyy
, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.
Since id is an attribute don't create an id element, just do this:
myPara.setAttribute("id", "id_you_like");
Try this. It's the easiest & most efficient way
<style name="datepicker" parent="Theme.AppCompat.Light.Dialog">
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primary_dark</item>
<item name="colorAccent">@color/primary</item>
</style>
Since you don't care, I chose the max ID for each number.
select tbl.* from tbl
inner join (
select max(id) as maxID, number from tbl group by number) maxID
on maxID.maxID = tbl.id
Query Explanation
select
tbl.* -- give me all the data from the base table (tbl)
from
tbl
inner join ( -- only return rows in tbl which match this subquery
select
max(id) as maxID -- MAX (ie distinct) ID per GROUP BY below
from
tbl
group by
NUMBER -- how to group rows for the MAX aggregation
) maxID
on maxID.maxID = tbl.id -- join condition ie only return rows in tbl
-- whose ID is also a MAX ID for a given NUMBER
Try the following:
int[][] multi = new int[5][10];
... which is a short hand for something like this:
int[][] multi = new int[5][];
multi[0] = new int[10];
multi[1] = new int[10];
multi[2] = new int[10];
multi[3] = new int[10];
multi[4] = new int[10];
Note that every element will be initialized to the default value for int
, 0
, so the above are also equivalent to:
int[][] multi = new int[][]{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
If you're using a framework like Twitter bootstrap you could simply add class "btn" to an a tag -- I just had a user call in about this problem apparently my checkout button wasn't working because I had a button inside an a tag... instead I just added the btn class to it and it works perfectly now.. Big mistake, one that probably cost customers -- and I sometimes forget to code check everything works in IE..
E.g.
<a href="link.com" class="btn" >Checkout</a>
Go to your project folder\app\src\main\res\mipmap-mdpi\ic_launcher.png
You will see 5 mipmap folders. Replace the icon inside of the each mipmap folder, with the icon you want.
Because most of solutions is bit outdated I could also suggest asciitable which already available in maven (de.vandermeer:asciitable:0.3.2
) and may produce very complicated configurations.
And usage still looks easy:
AsciiTable at = new AsciiTable();
at.addRule();
at.addRow("row 1 col 1", "row 1 col 2");
at.addRule();
at.addRow("row 2 col 1", "row 2 col 2");
at.addRule();
System.out.println(at.render()); // Finally, print the table to standard out.
It's not consistent across vendors - Oracle, MySQL, and DB2 support dual:
SELECT 'Hello world'
FROM DUAL
...while SQL Server, PostgreSQL, and SQLite don't require the FROM DUAL
:
SELECT 'Hello world'
MySQL does support both ways.
Action normally specifies the file/page that the form is submitted to (using the method described in the method paramater (post, get etc.))
An action of #
indicates that the form stays on the same page, simply suffixing the url with a #
. Similar use occurs in anchors. <a href=#">Link</a>
for example, will stay on the same page.
Thus, the form is submitted to the same page, which then processes the data etc.
You can pass array of variables to the compact as an arguement eg:
return view('yourView', compact(['var1','var2',....'varN']));
in view: if var1 is an object you can use it something like this
@foreach($var1 as $singleVar1)
{{$singleVar1->property}}
@endforeach
incase of single variable you can simply
{{$var2}}
i have done this several times without any issues
var thisRegex = new RegExp('\[(\d+)\]\[(\d+)\]');
if(!thisRegex.test(text)){
alert('fail');
}
I found test to act more preg_match as it provides a Boolean return. However you do have to declare a RegExp var.
TIP: RegExp adds it's own / at the start and finish, so don't pass them.
I'm not sure what problem you are solving, but when I have two side by side containers that need to be the same height, I run a little javascript on page load that finds the maximum height of the two and explicitly sets the other to the same height. It seems to me that height: 100% might just mean "make it the size needed to fully contain the content" when what you really want is "make both the size of the largest content."
Note: you'll need to resize them again if anything happens on the page to change their height -- like a validation summary being made visible or a collapsible menu opening.
If you're able to run PHP scripts you can give PHP MongoDB Admin a try. It's a single PHP script that gives you basic management and searching functionality.
I see you try to set ylim
but you give bad values. This will change the scale of the plot (like a zoom). For example see this:
par(mfrow=c(2,1))
tN <- table(Ni <- stats::rpois(100, lambda = 5))
r <- barplot(tN, col = rainbow(20),ylim=c(0,50),main='long y-axis')
r <- barplot(tN, col = rainbow(20),main='short y axis')
Another option is to plot without axes and set them manually using axis
and usr
:
require(grDevices) # for colours
par(mfrow=c(1,1))
r <- barplot(tN, col = rainbow(20),main='short y axis',ann=FALSE,axes=FALSE)
usr <- par("usr")
par(usr=c(usr[1:2], 0, 20))
axis(2,at=seq(0,20,5))
You should use a KeyGenerator to generate the Key,
AES key lengths are 128, 192, and 256 bit depending on the cipher you want to use.
Take a look at the tutorial here
Here is the code for Password Based Encryption, this has the password being entered through System.in you can change that to use a stored password if you want.
PBEKeySpec pbeKeySpec;
PBEParameterSpec pbeParamSpec;
SecretKeyFactory keyFac;
// Salt
byte[] salt = {
(byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
(byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
};
// Iteration count
int count = 20;
// Create PBE parameter set
pbeParamSpec = new PBEParameterSpec(salt, count);
// Prompt user for encryption password.
// Collect user password as char array (using the
// "readPassword" method from above), and convert
// it into a SecretKey object, using a PBE key
// factory.
System.out.print("Enter encryption password: ");
System.out.flush();
pbeKeySpec = new PBEKeySpec(readPassword(System.in));
keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
// Create PBE Cipher
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
// Initialize PBE Cipher with key and parameters
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
// Our cleartext
byte[] cleartext = "This is another example".getBytes();
// Encrypt the cleartext
byte[] ciphertext = pbeCipher.doFinal(cleartext);
I too had the similar problem. But in my case, the cause of the issue was due to the presence of apostrophes (i.e. single quotation marks) within some of the text values. This is especially frequent when working with data including texts in French, e.g. «L'autre jour».
So, the solution was simply to adjust the default setting of the quote argument to exclude the «'» symbol, and thus, using quote = "\"" (i.e. double quotation mark only), everything worked fine.
I hope that can help some of you. Cheers.
Run the Process Monitor to see what resources(Network, File, Registry, Threads) are being consumed and see any unnecessary resource(remote https, costly file reads) are being consumed
I had similar problem. When I run the process monitor I found that my fusion log is enabled so there are many into the disk which delayed the loading of dll after disabling fusion log IIS Express it is faster.
Go to MySQL installer and click Reconfigure (don't change any existing settings). This should start the server and you'll be off.
for run phpunit test in laravel by many way ..
vendor/bin/phpunit --filter methodName className pathTofile.php
vendor/bin/phpunit --filter 'namespace\\directoryName\\className::methodName'
for test single class :
vendor/bin/phpunit --filter tests/Feature/UserTest.php
vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest'
vendor/bin/phpunit --filter 'UserTest'
for test single method :
vendor/bin/phpunit --filter testExample
vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest::testExample'
vendor/bin/phpunit --filter testExample UserTest tests/Feature/UserTest.php
for run tests from all class within namespace :
vendor/bin/phpunit --filter 'Tests\\Feature'
for more way run test see more
In fact, your data is not well design. You'd better use something like :
$scope.steps = [
{stepName: "companyName", isComplete: true},
{stepName: "businessType", isComplete: true},
{stepName: "physicalAddress", isComplete: true}
];
Then it is easy to do what you want :
<div ng-repeat="step in steps">
Step {{step.stepName}} status : {{step.isComplet}}
</div>
Example: http://jsfiddle.net/rX7ba/
You don't want git revert
. That undoes a previous commit. You want git checkout
to get git's version of the file from master.
git checkout -- filename.txt
In general, when you want to perform a git operation on a single file, use -- filename
.
2020 Update
Git introduced a new command git restore
in version 2.23.0
. Therefore, if you have git version 2.23.0+
, you can simply git restore filename.txt
- which does the same thing as git checkout -- filename.txt
. The docs for this command do note that it is currently experimental.
To select data in numerical range you can use BETWEEN
which is inclusive.
SELECT JOB FROM MYTABLE WHERE ID BETWEEN 10 AND 15;
You could also try listing the css in the style sheet as !important
The solution discussed here worked well for me. This solution uses built-in cuda functions and is very simple to implement.
The relevant code is copied below:
#include <stdio.h>
#include <stdlib.h>
__global__ void foo(int *ptr)
{
*ptr = 7;
}
int main(void)
{
foo<<<1,1>>>(0);
// make the host block until the device is finished with foo
cudaDeviceSynchronize();
// check for error
cudaError_t error = cudaGetLastError();
if(error != cudaSuccess)
{
// print the CUDA error message and exit
printf("CUDA error: %s\n", cudaGetErrorString(error));
exit(-1);
}
return 0;
}
Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building RGBA -> JPG + BG
support for sorl thumbnails.
from PIL import Image
png = Image.open(object.logo.path)
png.load() # required for png.split()
background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel
background.save('foo.jpg', 'JPEG', quality=80)
Result @80%
Result @ 50%
Here's another way:
fist_segment = "hello,"
second_segment = "world."
complete_string = "#{first_segment} #{second_segment}"
Some more alternative options because regexes (regi ?) are awesome!
Here is a Simple regex to do the job:
regex="[^/]*$"
Example (grep):
FP="/hello/world/my/file/path/hello_my_filename.log"
echo $FP | grep -oP "$regex"
#Or using standard input
grep -oP "$regex" <<< $FP
Example (awk):
echo $FP | awk '{match($1, "$regex",a)}END{print a[0]}
#Or using stardard input
awk '{match($1, "$regex",a)}END{print a[0]} <<< $FP
If you need a more complicated regex: For example your path is wrapped in a string.
StrFP="my string is awesome file: /hello/world/my/file/path/hello_my_filename.log sweet path bro."
#this regex matches a string not containing / and ends with a period
#then at least one word character
#so its useful if you have an extension
regex="[^/]*\.\w{1,}"
#usage
grep -oP "$regex" <<< $StrFP
#alternatively you can get a little more complicated and use lookarounds
#this regex matches a part of a string that starts with / that does not contain a /
##then uses the lazy operator ? to match any character at any amount (as little as possible hence the lazy)
##that is followed by a space
##this allows use to match just a file name in a string with a file path if it has an exntension or not
##also if the path doesnt have file it will match the last directory in the file path
##however this will break if the file path has a space in it.
regex="(?<=/)[^/]*?(?=\s)"
#to fix the above problem you can use sed to remove spaces from the file path only
## as a side note unfortunately sed has limited regex capibility and it must be written out in long hand.
NewStrFP=$(echo $StrFP | sed 's:\(/[a-z]*\)\( \)\([a-z]*/\):\1\3:g')
grep -oP "$regex" <<< $NewStrFP
Total solution with Regexes:
This function can give you the filename with or without extension of a linux filepath even if the filename has multiple "."s in it. It can also handle spaces in the filepath and if the file path is embedded or wrapped in a string.
#you may notice that the sed replace has gotten really crazy looking
#I just added all of the allowed characters in a linux file path
function Get-FileName(){
local FileString="$1"
local NoExtension="$2"
local FileString=$(echo $FileString | sed 's:\(/[a-zA-Z0-9\<\>\|\\\:\)\(\&\;\,\?\*]*\)\( \)\([a-zA-Z0-9\<\>\|\\\:\)\(\&\;\,\?\*]*/\):\1\3:g')
local regex="(?<=/)[^/]*?(?=\s)"
local FileName=$(echo $FileString | grep -oP "$regex")
if [[ "$NoExtension" != "" ]]; then
sed 's:\.[^\.]*$::g' <<< $FileName
else
echo "$FileName"
fi
}
## call the function with extension
Get-FileName "my string is awesome file: /hel lo/world/my/file test/path/hello_my_filename.log sweet path bro."
##call function without extension
Get-FileName "my string is awesome file: /hel lo/world/my/file test/path/hello_my_filename.log sweet path bro." "1"
If you have to mess with a windows path you can start with this one:
[^\\]*$
<link rel="SHORTCUT ICON" href="favicon.ico" type="image/x-icon" />
<link rel="ICON" href="favicon.ico" type="image/ico" />
Excellent tool for cross-browser favicon - http://www.convertico.com/
In short there's no way to recover the passphrase for a pair of SSH keys. Why? Because it was intended this way in the first place for security reasons. The answers the other people gave you are all correct ways to CHANGE the password of your keys, not to recover them. So if you've forgotten your passphrase, the best you can do is create a new pair of SSH keys. Here's how to generate SSH keys and add it to your GitHub account.
There are three states of button
button
button:hover
button:active
Normal:
.button
{
//your css
}
Active
.button:active
{
//your css
}
Hover
.button:hover
{
//your css
}
SNIPPET:
Use :active
to style the active state of button.
button:active{_x000D_
background-color:red;_x000D_
}
_x000D_
<button>Click Me</button>
_x000D_
vim +21490go script.py
From the command line will open the file and take you to position 21490
in the buffer.
Triggering it from the command line like this allows you to automate a script to parse the exception message and open the file to the problem position.
Excerpt from man vim
:
+{command} -c {command}
{command}
will be executed after the first file has been read.{command}
is interpreted as an Ex command. If the{command}
contains spaces it must be enclosed in double quotes (this depends on the shell that is used).
I think this should do it for you.
assertThrows(someException.class, ()-> mockedServiceReference.someMethod(param1,parme2,..));
Make sure the WOExerciseListViewController is a Target Member; that worked for me!
Simplest form I ever found is...
List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));
Wrap your input stream in a buffered reader then use the read method to read one byte at a time until the end of stream.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Reader {
public static void main(String[] args) throws IOException {
BufferedReader buffer = new BufferedReader(
new InputStreamReader(System.in));
int c = 0;
while((c = buffer.read()) != -1) {
char character = (char) c;
System.out.println(character);
}
}
}
>>> import pandas as pd
>>> df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})
>>> df
x y
0 1 4
1 2 5
2 3 6
3 4 7
>>> s = df.ix[:,0]
>>> type(s)
<class 'pandas.core.series.Series'>
>>>
===========================================================================
UPDATE
If you're reading this after June 2017, ix
has been deprecated in pandas 0.20.2, so don't use it. Use loc
or iloc
instead. See comments and other answers to this question.
It means that you compiled your classes under a specific JDK, but then try to run them under older version of JDK.
This regex can help you to check your email-address according to all the criteria which gmail.com used.
var re = /^\w+([-+.'][^\s]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var emailFormat = re.test($("#email").val()); // This return result in Boolean type
if (emailFormat) {}
No my friend its very simple, try using this:
AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to dear user.");
alertDialog.setIcon(R.drawable.welcome);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
This tutorial shows how you can create custom dialog using xml and then show them as an alert dialog.
I'm a bit late to the party but I needed to implement a general solution and it turned out that none of the solutions can satisfy my needs.
The accepted solution is good for small ranges; however, maximum - minimum
can be infinity for big ranges. So a corrected version can be this version:
public static double NextDoubleLinear(this Random random, double minValue, double maxValue)
{
// TODO: some validation here...
double sample = random.NextDouble();
return (maxValue * sample) + (minValue * (1d - sample));
}
This generates random numbers nicely even between double.MinValue
and double.MaxValue
. But this introduces another "problem", which is nicely presented in this post: if we use such big ranges the values might seem too "unnatural". For example, after generating 10,000 random doubles between 0 and double.MaxValue
all of the values were between 2.9579E+304 and 1.7976E+308.
So I created also another version, which generates numbers on a logarithmic scale:
public static double NextDoubleLogarithmic(this Random random, double minValue, double maxValue)
{
// TODO: some validation here...
bool posAndNeg = minValue < 0d && maxValue > 0d;
double minAbs = Math.Min(Math.Abs(minValue), Math.Abs(maxValue));
double maxAbs = Math.Max(Math.Abs(minValue), Math.Abs(maxValue));
int sign;
if (!posAndNeg)
sign = minValue < 0d ? -1 : 1;
else
{
// if both negative and positive results are expected we select the sign based on the size of the ranges
double sample = random.NextDouble();
var rate = minAbs / maxAbs;
var absMinValue = Math.Abs(minValue);
bool isNeg = absMinValue <= maxValue ? rate / 2d > sample : rate / 2d < sample;
sign = isNeg ? -1 : 1;
// now adjusting the limits for 0..[selected range]
minAbs = 0d;
maxAbs = isNeg ? absMinValue : Math.Abs(maxValue);
}
// Possible double exponents are -1022..1023 but we don't generate too small exponents for big ranges because
// that would cause too many almost zero results, which are much smaller than the original NextDouble values.
double minExponent = minAbs == 0d ? -16d : Math.Log(minAbs, 2d);
double maxExponent = Math.Log(maxAbs, 2d);
if (minExponent == maxExponent)
return minValue;
// We decrease exponents only if the given range is already small. Even lower than -1022 is no problem, the result may be 0
if (maxExponent < minExponent)
minExponent = maxExponent - 4;
double result = sign * Math.Pow(2d, NextDoubleLinear(random, minExponent, maxExponent));
// protecting ourselves against inaccurate calculations; however, in practice result is always in range.
return result < minValue ? minValue : (result > maxValue ? maxValue : result);
}
Some tests:
Here are the sorted results of generating 10,000 random double numbers between 0 and Double.MaxValue
with both strategies. The results are displayed with using logarithmic scale:
Though the linear random values seem to be wrong at first glance the statistics show that none of them are "better" than the other: even the linear strategy has an even distribution and the average difference between the values are pretty much the same with both strategies.
Playing with different ranges showed me that the linear strategy gets to be "sane" with range between 0 and ushort.MaxValue
with a "reasonable" minimum value of 10.78294704
(for ulong
range the minimum value was 3.03518E+15; int
: 353341). These are the same results of both strategies displayed with different scales:
Edit:
Recently I made my libraries open source, feel free to see the RandomExtensions.NextDouble
method with the complete validation.
You may add a div with position:absolute
within a table/div with position:relative
. For example, if you want your overlay div to be shown at the bottom right of the main text div (width and height can be removed):
<div style="position:relative;width:300px;height:300px;background-color:#eef">
<div style="position:absolute;bottom:0;right:0;width:100px;height:100px;background-color:#fee">
I'm over you!
</div>
Your main text
</div>
See it here: http://jsfiddle.net/bptvt5kb/
I solve the problem opening the visual studio, expanding the references and changing the property "Copy Local" to "True".
I discover this comparing the dlls of the old version with the Dlls of my new version (that was not working)
From my point of view the best way to manage multiple conditional props is the props object approach from @brigand. But it can be improved in order to avoid adding one if
block for each conditional prop.
rename it as you like (iv, condVal, cv, _, ...)
You can define a helper function to return a value, or another, if a condition is met:
// components-helpers.js
export const ifVal = (cond, trueValue=true, falseValue=null) => {
return cond ? trueValue : falseValue
}
If cond
is true
(or truthy), the trueValue
is returned - or true
.
If cond
is false
(or falsy), the falseValue
is returned - or null
.
These defaults (true
and null
) are, usually the right values to allow a prop to be passed or not to a React component. You can think to this function as an "improved React ternary operator". Please improve it if you need more control over the returned values.
Let's use it with many props.
// your-code.js
import { ifVal } from './components-helpers.js'
// BE SURE to replace all true/false with a real condition in you code
// this is just an example
const inputProps = {
value: 'foo',
enabled: ifVal(true), // true
noProp: ifVal(false), // null - ignored by React
aProp: ifVal(true, 'my value'), // 'my value'
bProp: ifVal(false, 'the true text', 'the false text') // 'my false value',
onAction: ifVal(isGuest, handleGuest, handleUser) // it depends on isGuest value
};
<MyComponent {...inputProps} />
This approach is something similar to the popular way to conditionally manage classes using the classnames utility, but adapted to props.
You'll have a clean and readable syntax, even with many conditional props: every new prop just add a line of code inside the object declaration.
In this way you replace the syntax noise of repeated operators (...
, &&
, ? :
, ...), that can be very annoying when you have many props, with a plain function call.
Our top priority, as developers, is to write the most obvious code that solve a problem. Too many times we solve problems for our ego, adding complexity where it's not required. Our code should be straightforward, for us today, for us tomorrow and for our mates.
just because we can do something doesn't mean we should
I hope this late reply will help.
You are looking for JavaScript's String
method substring
e.g.
'Hiya how are you'.substring(0,8);
Which returns the string starting at the first character and finishing before the 9th character - i.e. 'Hiya how'.
I have a 32-bit Python 3.5 on a 64-bit Windows 8.1 machine. I just tried almost every way I can find on Stack Overflow and no one works!
Then on here I found it. It says:
SciPy is software for mathematics, science, and engineering.
Requires numpy+mkl.
Install numpy+mkl before installing scipy.
mkl matters!! But nobody said anything about that before!
Then I installed mkl:
C:\Users\****\Desktop\a> pip install mkl_service-1.1.2-cp35-cp35m-win32.whl
Processing c:\users\****\desktop\a\mkl_service-1.1.2-cp35-cp35m-win32.whl
Installing collected packages: mkl-service
Successfully installed mkl-service-1.1.2
Then I installed SciPy:
C:\Users\****\Desktop\a>pip install scipy-0.18.1-cp35-cp35m-win32.whl
Processing c:\users\****\desktop\a\scipy-0.18.1-cp35-cp35m-win32.whl
Installing collected packages: scipy
Successfully installed scipy-0.18.1
It worked~ yeah :)
A tip: You can just google "whl_file_name.whl" to know where to download it~ :)
Update:
After all these steps you will find that you still can not use SciPy in Python 3. If you print "import scipy" you will find there are error messages, but don't worry, there is only one more thing to do. Here ——just comment out that line, simple and useful.
from numpy._distributor_init import NUMPY_MKL
I promise that it is the last thing to do :)
PS: Before all these steps, you better install NumPy first. That's very simple using this command:
pip install numpy
npm i
"npm i
" will not only install missing deps, it updates node_modules to match the package.json
Outside of the performance (non)issues, I think the biggest failing of cursors is they are painful to debug. Especially compared to code in most client applications where debugging tends to be comparatively easy and language features tend to be much easier. In fact, I contend that nearly anything one is doing in SQL with a cursor should probably be happening in the client app in the first place.