There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
To return the whole table at once you could change the SELECT to:
SELECT ...
BULK COLLECT INTO T
FROM ...
This is only advisable for results that aren't excessively large, since they all have to be accumulated in memory before being returned; otherwise consider the pipelined function as suggested by Charles, or returning a REF CURSOR.
I can attest to the fact that -webkit-transform: translate3d(0, 0, 0);
will mess with the new position: -webkit-sticky;
property. With a left drawer navigation pattern that I was working on, the hardware acceleration I wanted with the transform property was messing with the fixed positioning of my top nav bar. I turned off the transform and the positioning worked fine.
Luckily, I seem to have had hardware acceleration on already, because I had -webkit-font-smoothing: antialiased
on the html element. I was testing this behavior in iOS7 and Android.
Send a POST request with content type = 'form-data':
import requests
files = {
'username': (None, 'myusername'),
'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)
If you are looking to count the number of NAs in the entire dataframe you could also use
sum(is.na(df))
Dragon NaturallySpeaking seems to support MP3 input.
If you want an open source version (I think there are some Asterisk integration projects based on this one).
If you're getting error TS1005: 'finally' expected.
, it means you forgot to implement catch
after try
. Generally, it means the syntax you attempted to use was incorrect.
I suggest you to see "How do I run a bat file in the background from another bat file?"
Also, good answer (of using start
command) was given in "Parallel execution of shell processes" question page here;
But my recommendation is to use PowerShell. I believe it will perfectly suit your needs.
If you are on windows. Open your cmd at right folder then first
set node_env={your env name here}
hit enter then you can start your node with
node app.js
it will start with your env setting
Basically, an integer n is a power of three, if there exists an integer x such that n == 3x.
So to verify that you can use this functions
def is_power_of_three(n)
return false unless n.positive?
n == 3**(Math.log10(n)/Math.log10(3)).to_f.round(2)
end
First check the variables declared using proper Datatypes. I had a same problem then I have checked, by mistake I declared SAPUser as int datatype so that the error occurred. One more thing XML file stores its data using concept like array but its first index starts having +1. e.g. if error is in(7,2) then check for 6th line always.....
MySQL unique and primary keys serve to identify rows. There can be only one Primary key in a table but one or more unique keys. Key is just index.
for more details you can check http://www.geeksww.com/tutorials/database_management_systems/mysql/tips_and_tricks/mysql_primary_key_vs_unique_key_constraints.php
to convert mysql to mssql try this and see http://gathadams.com/2008/02/07/convert-mysql-to-ms-sql-server/
All Answers are right, but i still want to give some other alternatives that may work.
If you are looking for the assigned width (ignoring padding, margin and so on) you could use.
getComputedStyle(element).width; //returns value in px like "727.7px"
getComputedStyle allows you to access all styles of that elements. For example: padding, paddingLeft, margin, border-top-left-radius and so on.
Yes, but don't - escaping forward slashes is a good thing. When using JSON inside <script>
tags it's necessary as a </script>
anywhere - even inside a string - will end the script tag.
Depending on where the JSON is used it's not necessary, but it can be safely ignored.
I used pekka's pattern. I think yet another pattern.
<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">
and parsed querystring in myjsfile.js.
To quote the specifications:
The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.
The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's
__init__.py
module) should also list the modules and subpackages exported by the package.The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its
__init__
method. Individual methods should be documented by their own docstring.
The docstring of a function or method is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.
Solve it by placing the following include files and definition first:
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
In your database table list it should show View in Type column. To edit View:
Hope this help
update: in PHPMyAdmin 4.x, it doesn't show View in Type, but you can still recognize it:
Of course it may be just an empty table, but when you open the structure, you will know whether it's a table or a view.
I would recomend using templates of some sort. There are various different ways to approach this but essentially hold a template of the Email some where (on disk, in a database etc) and simply insert the key data (IE: Recipients name etc) into the template.
This is far more flexible because it means you can alter the template as required without having to alter your code. In my experience your likely to get requests for changes to the templates from end users. If you want to go the whole hog you could include a template editor.
I'm an Android newbie but here is the timer class I created based on the answers above. It works for my app but I welcome any suggestions.
Usage example:
...{
public Handler uiHandler = new Handler();
private Runnable runMethod = new Runnable()
{
public void run()
{
// do something
}
};
timer = new UITimer(handler, runMethod, timeoutSeconds*1000);
timer.start();
}...
public class UITimer
{
private Handler handler;
private Runnable runMethod;
private int intervalMs;
private boolean enabled = false;
private boolean oneTime = false;
public UITimer(Handler handler, Runnable runMethod, int intervalMs)
{
this.handler = handler;
this.runMethod = runMethod;
this.intervalMs = intervalMs;
}
public UITimer(Handler handler, Runnable runMethod, int intervalMs, boolean oneTime)
{
this(handler, runMethod, intervalMs);
this.oneTime = oneTime;
}
public void start()
{
if (enabled)
return;
if (intervalMs < 1)
{
Log.e("timer start", "Invalid interval:" + intervalMs);
return;
}
enabled = true;
handler.postDelayed(timer_tick, intervalMs);
}
public void stop()
{
if (!enabled)
return;
enabled = false;
handler.removeCallbacks(runMethod);
handler.removeCallbacks(timer_tick);
}
public boolean isEnabled()
{
return enabled;
}
private Runnable timer_tick = new Runnable()
{
public void run()
{
if (!enabled)
return;
handler.post(runMethod);
if (oneTime)
{
enabled = false;
return;
}
handler.postDelayed(timer_tick, intervalMs);
}
};
}
When you say the 'GUI Tool', I assume you're using Git For Windows.
IMPORTANT, I would highly recommend creating a new branch to do this on if you haven't already. That way your master can remain the same while you test out your changes.
With the GUI you need to 'roll back this commit' like you have with the history on the right of your view. Then you will notice you have all the unwanted files as changes to commit on the left. Now you need to right click on the grey title above all the uncommited files and select 'disregard changes'. This will set your files back to how they were in this version.
Here's my take on it. I needed to create a URL by collecting the value from a text box , when the user presses a Submit button.
<html>_x000D_
<body>_x000D_
_x000D_
Hi everyone_x000D_
_x000D_
<p id="result"></p>_x000D_
_x000D_
<textarea cols="40" id="SearchText" rows="2"></textarea>_x000D_
_x000D_
<button onclick="myFunction()" type="button">Submit!</button>_x000D_
_x000D_
<script>_x000D_
function myFunction() {_x000D_
var result = document.getElementById("SearchText").value;_x000D_
document.getElementById("result").innerHTML = result;_x000D_
document.getElementById("abc").href="http://arindam31.pythonanywhere.com/hello/" + result;_x000D_
} _x000D_
</script>_x000D_
_x000D_
_x000D_
<a href="#" id="abc">abc</a>_x000D_
_x000D_
</body>_x000D_
<html>
_x000D_
You can use <br/><br/>
or
or \ \
.
I tried {CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;}
but it didn`t work for me, since my UI culture was different from my number/currency culture. So I suggest you to use:
CultureInfo currentCulture = Thread.CurrentThread.CurrentUICulture;
This will give you the culture your UI is (texts on windows, message boxes, etc).
The correct pattern is to call the Redirect overload with endResponse=false and make a call to tell the IIS pipeline that it should advance directly to the EndRequest stage once you return control:
Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();
This blog post from Thomas Marquardt provides additional details, including how to handle the special case of redirecting inside an Application_Error handler.
You need to hook to console exit event and not your process.
http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx
According to http://www.techotopia.com/index.php/Ruby_String_Concatenation_and_Comparison
Doing either
mystring == yourstring
or
mystring.eql? yourstring
Are equivalent.
You need a public class for Form1 to initialize.
See this code:
namespace TimerApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int counter = 60;
private void button1_Click(object sender, EventArgs e)
{
//Insert your code from before
}
private void timer1_Tick(object sender, EventArgs e)
{
//Again insert your code
}
}
}
I've tried this and it all worked fine
If you need anymore help feel free to comment :)
if (ConfigurationManager.AppSettings.AllKeys.Contains("myKey"))
{
// Key exists
}
else
{
// Key doesn't exist
}
According to the release-notes, Java 11 removed the Java EE modules:
java.xml.bind (JAXB) - REMOVED
See JEP 320 for more info.
You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.3</version>
<scope>runtime</scope>
</dependency>
Use latest release of Eclipse Implementation of JAXB 3.0.0:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*
, so update import statements:
javax.xml.bind -> jakarta.xml.bind
Here Is my snippet try it. I hope it will helpfull for u.
<!DOCTYPE HTML>_x000D_
<html>_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
<title>Untitled Document</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<div id="hello"></div>_x000D_
_x000D_
<script type ="text/javascript">_x000D_
what();_x000D_
function what(){_x000D_
document.getElementById('hello').innerHTML = 'hi';_x000D_
};_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
Well, I faced the same issue. For new users who may land at this page. Just follow their official documentation.
Install flask-cors
pip install -U flask-cors
then after app initialization, initialize flask-cors
with default arguments:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"
In my case I faced this issue in my simulator because my computer's date was behind of current date. So do check this case too when you face SSL error.
You can't, this is determined by the browser, for the user's safety and security. For example you can't make it say "Virus detected" with a message of "Would you like to quarantine it now?"...at least not as an alert()
.
There are plenty of JavaScript Modal Dialogs out there though, that are far more customizable than alert()
.
I had the same problem. The problem was that the labels were in a column format while it expected it in a row.
use np.ravel()
knn.score(training_set, np.ravel(training_labels))
Hope this solves it.
To remove spaces from left/right, use LTRIM/RTRIM. What you had
UPDATE *tablename*
SET *columnname* = LTRIM(RTRIM(*columnname*));
would have worked on ALL the rows. To minimize updates if you don't need to update, the update code is unchanged, but the LIKE expression in the WHERE clause would have been
UPDATE [tablename]
SET [columnname] = LTRIM(RTRIM([columnname]))
WHERE 32 in (ASCII([columname]), ASCII(REVERSE([columname])));
Note: 32 is the ascii code for the space character.
Explaining if any one want to send some parameters while calling stored procedure as below,
using (SqlConnection con = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(storedProcName, con))
{
foreach (var item in sqlParams)
{
item.Direction = ParameterDirection.Input;
item.DbType = DbType.String;
command.Parameters.Add(item);
}
command.CommandType = CommandType.StoredProcedure;
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(dt);
}
}
}
You can get the current username on Windows by going through the Windows API, although it's a bit cumbersome to invoke via the ctypes FFI (GetCurrentProcess ? OpenProcessToken ? GetTokenInformation ? LookupAccountSid).
I wrote a small module that can do this straight from Python, getuser.py. Usage:
import getuser
print(getuser.lookup_username())
It works on both Windows and *nix (the latter uses the pwd
module as described in the other answers).
Based on drspaceboo's solution, with Kotlin you can use an extension to convert Float
to dips more easily.
fun Float.toDips() =
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, resources.displayMetrics);
Usage:
(65f).toDips()
Free and easy method:
If your target user base is not large(less than a 1000) and you want a free service to start with, then Airbop is the best and most convenient.
Airbop Website It uses Google Cloud Messaging service through its API and is provides a good performance. i have used it for two of my projects and it was easy implementing it.
Services like and Urbanship are excellent but provide an entire deployment stack and not just the push notifications thing.
If only push service is your target, Airbop will work fine.
I haven't used Pushwoosh, but is also a great choice. It allows push to 1,000,000 devices for free
To be able to give you specific help, you's have to explain what particular parts specifically "get messed up", or perhaps offer a screenshot. It also helps to know what version of Outlook you encounter the problem in.
Either way, CampaignMonitor.com's CSS guide has often helped me out debugging email client inconsistencies.
From that guide you can see several things just won't work well or at all in Outlook, here are some highlights of the more important ones:
E:first-child
, E:hover
, E > F
(Child combinator), E + F
(Adjacent sibling combinator), E ~ F
(General sibling combinator). This unfortunately means resorting to workarounds like inline styles.white-space
won't work.background-image
property won't work.height
, width
, and the max-
versions are either not usable or have bugs for certain elements.display
, float
s and position
are all out).In short: combining CSS and Outlook can be a pain. Be prepared to use many ugly workarounds.
PS. In your specific case, there are two minor issues in your html that may cause you odd behavior. There's "align=top
" where you probably meant to use vertical-align
. Also: cell-padding
for td
s doesn't exist.
You were close
/my/bash/script <<< 'This string will be sent to stdin.'
For multiline input, here-docs are suited:
/my/bash/script <<STDIN -o other --options
line 1
line 2
STDIN
Edit To the comments:
To achieve binary input, say
xxd -r -p <<BINARY | iconv -f UCS-4BE -t UTF-8 | /my/bash/script
0000 79c1 0000 306f 0000 3061 0000 3093 0000 3077 0000 3093 0000 304b 0000 3093 0000 3077 0000 3093 0000 306a 0000 8a71 0000 306b 0000 30ca 0000 30f3 0000 30bb
0000 30f3 0000 30b9 0000 3092 0000 7ffb 0000 8a33 0000 3059 0000 308b 0000 3053 0000 3068 0000 304c 0000 3067 0000 304d 0000 000a
BINARY
If you substitute cat
for /my/bash/script
(or indeed drop the last pipe), this prints:
????????????????????????????
Or, if you wanted something a little more geeky:
0000000: 0000 0000 bef9 0e3c 59f8 8e3c 0a71 d63c .......<Y..<.q.<
0000010: c6f2 0e3d 3eaa 323d 3a5e 563d 090e 7a3d ...=>.2=:^V=..z=
0000020: 7bdc 8e3d 2aaf a03d b67e b23d c74a c43d {..=*..=.~.=.J.=
0000030: 0513 d63d 16d7 e73d a296 f93d a8a8 053e ...=...=...=...>
0000040: 6583 0e3e 5a5b 173e 5b30 203e 3d02 293e e..>Z[.>[0 >=.)>
0000050: d4d0 313e f39b 3a3e 6f63 433e 1c27 4c3e ..1>..:>ocC>.'L>
0000060: cde6 543e 59a2 5d3e 9259 663e 4d0c 6f3e ..T>Y.]>.Yf>M.o>
0000070: 60ba 773e cf31 803e ee83 843e 78d3 883e `.w>.1.>...>x..>
0000080: 5720 8d3e 766a 913e beb1 953e 1cf6 993e W .>vj.>...>...>
0000090: 7a37 9e3e c275 a23e dfb0 a63e bce8 aa3e z7.>.u.>...>...>
00000a0: 441d af3e 624e b33e 017c b73e 0ca6 bb3e D..>bN.>.|.>...>
00000b0: 6fcc bf3e 15ef c33e e90d c83e d728 cc3e o..>...>...>.(.>
00000c0: c93f d03e ac52 d43e 6c61 d83e f36b dc3e .?.>.R.>la.>.k.>
00000d0: 2f72 e03e 0a74 e43e 7171 e83e 506a ec3e /r.>.t.>qq.>Pj.>
00000e0: 945e f03e 274e f43e f738 f83e f11e fc3e .^.>'N.>.8.>...>
00000f0: 0000 003f 09ee 013f 89d9 033f 77c2 053f ...?...?...?w..?
0000100: caa8 073f 788c 093f 776d 0b3f be4b 0d3f ...?x..?wm.?.K.?
0000110: 4427 0f3f 0000 113f e8d5 123f f3a8 143f D'.?...?...?...?
0000120: 1879 163f 4e46 183f 8d10 1a3f cad7 1b3f .y.?NF.?...?...?
0000130: fe9b 1d3f 1f5d 1f3f 241b 213f 06d6 223f ...?.].?$.!?.."?
0000140: bb8d 243f 3a42 263f 7cf3 273f 78a1 293f ..$?:B&?|.'?x.)?
0000150: 254c 2b3f 7bf3 2c3f 7297 2e3f 0138 303f %L+?{.,?r..?.80?
0000160: 22d5 313f ca6e 333f ".1?.n3?
Which is the sines of the first 90 degrees in 4byte binary floats
In Angular 8 , ViewChild takes 2 parameters
@ViewChild(ChildDirective, {static: false}) Component
You can do this using jQuery:
This method gets a list of its children then counts the length of that list, as simple as that.
$("ul").find("*").length;
The find() method traverses DOM downwards along descendants, all the way down to the last descendant.
Note: children() method traverses a single level down the DOM tree.
for(var i,a=[i=0];i<10;a[i++]=i);
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
When a variable is declared static inside a class then it becomes a shared variable for all objects of that class which means that the variable is longer specific to any object. For example: -
#include<iostream.h>
#include<conio.h>
class test
{
void fun()
{
static int a=0;
a++;
cout<<"Value of a = "<<a<<"\n";
}
};
void main()
{
clrscr();
test obj1;
test obj2;
test obj3;
obj1.fun();
obj2.fun();
obj3.fun();
getch();
}
This program will generate the following output: -
Value of a = 1
Value of a = 2
Value of a = 3
The same goes for globally declared static variable. The above code will generate the same output if we declare the variable a outside function void fun()
Whereas if u remove the keyword static and declare a as a non-static local/global variable then the output will be as follows: -
Value of a = 1
Value of a = 1
Value of a = 1
@P-A's solution partially works for me. Detail my findings below:
1) The first code snippet is incorrect, see below:
<activity
...
<intent-filter>
==> <action android:name="android.intent.action.MAIN" /> <== This line shouldn't be deleted, otherwise will have compile error
<category android:name="android.intent.category.LAUNCHER" /> //DELETE THIS LINE
</intent-filter>
</activity>
2) Should use following code to disable all icons before enabling another one, otherwise it will add a new icon, instead of replacing it.
getPackageManager().setComponentEnabledSetting(
getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
BUT, if you use code above, then shortcut on homescreen will be removed! And it won't be automatically added back. You might be able to programmatically add icon back, but it probably won't stay in the same position as before.
3) Note that the icon won't get changed immediately, it might take several seconds. If you click it right after changing, you might get an error saying: "App isn't installed".
So, IMHO this solution is only suitable for changing icon in app launcher only, not for shortcuts (i.e. the icon on homescreen)
on windows 10, Notepad 7.8.5, i found this solution to convert from CRLF to LF.
Edit > Format end of line
and choose either Windows(CR+LF)
or Unix(LF)
mytable:
Value ColOne
--------------------
1 Cleo, Smith
The following should work if there aren't too many columns
ALTER TABLE mytable ADD ColTwo nvarchar(256);
UPDATE mytable SET ColTwo = LEFT(ColOne, Charindex(',', ColOne) - 1);
--'Cleo' = LEFT('Cleo, Smith', Charindex(',', 'Cleo, Smith') - 1)
UPDATE mytable SET ColTwo = REPLACE(ColOne, ColTwo + ',', '');
--' Smith' = REPLACE('Cleo, Smith', 'Cleo' + ',')
UPDATE mytable SET ColOne = REPLACE(ColOne, ',' + ColTwo, ''), ColTwo = LTRIM(ColTwo);
--'Cleo' = REPLACE('Cleo, Smith', ',' + ' Smith', '')
Result:
Value ColOne ColTwo
--------------------
1 Cleo Smith
Just to improve YCR's answer:
1) I added black lines on x and y axis. Otherwise they are made transparent too.
2) I added a transparent theme to the legend key. Otherwise, you will get a fill there, which won't be very esthetic.
Finally, note that all those work only with pdf and png formats. jpeg fails to produce transparent graphs.
MyTheme_transparent <- theme(
panel.background = element_rect(fill = "transparent"), # bg of the panel
plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
panel.grid.major = element_blank(), # get rid of major grid
panel.grid.minor = element_blank(), # get rid of minor grid
legend.background = element_rect(fill = "transparent"), # get rid of legend bg
legend.box.background = element_rect(fill = "transparent"), # get rid of legend panel bg
legend.key = element_rect(fill = "transparent", colour = NA), # get rid of key legend fill, and of the surrounding
axis.line = element_line(colour = "black") # adding a black line for x and y axis
)
For anyone that wants to download jdk 8 without an oracle account: https://download.oracle.com/otn-pub/java/jdk/8u271-b09/61ae65e088624f5aaa0b1d2d801acb16/jdk-8u271-windows-x64.exe
copy and paste the link. Jdk 15 didn't work for me so i tried using jdk 8 and it worked.
2007 might be a bit complicated as well.
The .docx format is a zip file that contains a few folders with other files in them for formatting and other stuff.
Rename a .docx file to .zip and you'll see what I mean.
So if you can work within zip files in PHP, you should be on the right path.
First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:
I would use an anonymous type filled with your results
type:
string json = JsonConvert.SerializeObject(new
{
results = new List<Result>()
{
new Result { id = 1, value = "ABC", info = "ABC" },
new Result { id = 2, value = "JKL", info = "JKL" }
}
});
Also, note that the generated JSON has result items with id
s of type Number
instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id
to string
in the C#.
I'd also tweak your results
type and get rid of the backing fields:
public class Result
{
public int id { get ;set; }
public string value { get; set; }
public string info { get; set; }
}
Furthermore, classes conventionally are PascalCased
and not camelCased
.
Here's the generated JSON from the code above:
{
"results": [
{
"id": 1,
"value": "ABC",
"info": "ABC"
},
{
"id": 2,
"value": "JKL",
"info": "JKL"
}
]
}
As for Xcode 5.1, the problem was in arm64
architecture in VALID_ARCHS
. Building the release configuration for 5.0 device locally gives the following error:
Xcode cannot install or launch applications supporting the 64-bit architecture on devices running iOS versions prior to 6.0. This configuration is supported for distribution through the iOS App Store, but cannot be used during development with Xcode. To continue, edit the Run scheme action and select a build configuration that does not include the 64-bit architecture.
Removing arm64
from VALID_ARCHS
solves the issue. In my case I had to create a separate branch for testing on iOS 5 devices.
Make sure it's within a document ready tagAlternatively, try using .live
$(document).ready(function(){
$('#content').live('click', function(e) {
alert(1);
});
});
Example:
$(document).ready(function() {_x000D_
$('#content').click(function(e) { _x000D_
alert(1);_x000D_
});_x000D_
});
_x000D_
#content {_x000D_
padding: 20px;_x000D_
background: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id="content">Hello world</div>
_x000D_
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
$('#content').on( "click", function() {
alert(1);
});
There's a few different ways you can tackle this one.
You can set a counter before the foreach() and then just iterate through which is the easiest approach.
$counter = 0;
foreach ($Contents as $item) {
$counter++;
$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
The simple answer to solve your problem could be like this:
for i in range(100):
k = 100 - i
print(k)
The easiest way is
new = old[['A','C','D']]
.
As an alternative, and pretty close to debiasej approach. Since a SOAP request is just a HTTP request, you can simply perform a GET or POST using with HTTP client, but it's not mandatory to build SOAP envelope.
Something like this:
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace HGF.Infraestructure.Communications
{
public class SOAPSample
{
private readonly IHttpClientFactory _clientFactory;
private readonly ILogger<DocumentProvider> _logger;
public SOAPSample(ILogger<DocumentProvider> logger,
IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
_logger = logger;
}
public async Task<string> UsingGet(int value1, int value2)
{
try
{
var client = _clientFactory.CreateClient();
var response = await client.GetAsync($"https://hostname.com/webservice.asmx/SampleMethod?value1={value1}&value2={value2}", HttpCompletionOption.ResponseHeadersRead);
//NULL check, HTTP Status Check....
return await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Oops! Something went wrong");
return ex.Message;
}
}
public async Task<string> UsingPost(int value1, int value2)
{
try
{
var content = new StringContent($"value1={value1}&value2={value2}", Encoding.UTF8, "application/x-www-form-urlencoded");
var client = _clientFactory.CreateClient();
var response = await client.PostAsync("https://hostname.com/webservice.asmx/SampleMethod", content);
//NULL check, HTTP Status Check....
return await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Oops! Something went wrong");
return ex.Message;
}
}
}
}
Of course, it depends on your scenario. If the payload is too complex, then this won't work
Why not a/b/(c|d|e)
? I just tried with Saxon XML library (wrapped up nicely with some Clojure goodness), and it seems to work.
abc.xml
is the doc described by OP.
(require '[saxon :as xml])
(def abc-doc (xml/compile-xml (slurp "abc.xml")))
(xml/query "a/b/(c|d|e)" abc-doc)
=> (#<XdmNode <c>C1</c>>
#<XdmNode <d>D1</d>>
#<XdmNode <e>E1</e>>
#<XdmNode <c>C2</c>>
#<XdmNode <d>D2</d>>
#<XdmNode <e>E1</e>>)
With STL, programmers use iterators
for traversing through containers, since iterator is an abstract concept, implemented in all standard containers. For example, std::list
has no operator []
at all.
While you could use a continue
, why not just inverse the logic in your if?
while(rs.next())
{
if(!f.exists() || f.isDirectory()){
//proceed
}
}
You don't even need an else {continue;}
as it will continue anyway if the if
conditions are not satisfied.
Please check the Web Properties of the web (Asp.Net) project hosting your silverlight xap. Go to Web project Hosting your silverlight xap -> Properties -> Web -> Debuggers Section -> Make sure that silverlight checkbox is checked.
I don't know if this is new in sklearn
or pandas
, but I'm able to pass the data frame directly to sklearn
without converting the data frame to a numpy array or any other data types.
from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit(df[['B', 'C']], df['A'])
>>> reg.coef_
array([ 4.01182386e-01, 3.51587361e-04])
Had the same problem, needed to fit many markers on the map. This solved my case:
bounds.extend(objLatLng)
)Execute fitbounds AFTER map is completed:
google.maps.event.addListenerOnce(map, 'idle', function() {
map.fitBounds( bounds );
});
You could write yourself a little function to do what you want:
import random
def randomDigits(digits):
lower = 10**(digits-1)
upper = 10**digits - 1
return random.randint(lower, upper)
Basically, 10**(digits-1)
gives you the smallest {digit}-digit number, and 10**digits - 1
gives you the largest {digit}-digit number (which happens to be the smallest {digit+1}-digit number minus 1!). Then we just take a random integer from that range.
For a long value you need to add the length info 'l' and 'u' for unsigned decimal integer,
as a reference of available options see sprintf
#include <stdio.h>
int main ()
{
unsigned long lval = 123;
char buffer [50];
sprintf (buffer, "%lu" , lval );
}
If you're using MySQL Workbench, right-click a table and select alter table
.
In that window you can see your table Engine and also change it.
You can achieve the solution, by doing this:
JavaScript:
var myValue = document.getElementById("@(ViewBag.CC)").value;
or if you want to use jQuery
, then:
jQuery
var myValue = $('#' + '@(ViewBag.CC)').val();
LINQ:
Enumerable.Range(0, 1 + end.Subtract(start).Days)
.Select(offset => start.AddDays(offset))
.ToArray();
For loop:
var dates = new List<DateTime>();
for (var dt = start; dt <= end; dt = dt.AddDays(1))
{
dates.Add(dt);
}
EDIT: As for padding values with defaults in a time-series, you could enumerate all the dates in the full date-range, and pick the value for a date directly from the series if it exists, or the default otherwise. For example:
var paddedSeries = fullDates.ToDictionary(date => date, date => timeSeries.ContainsDate(date)
? timeSeries[date] : defaultValue);
There's also the function tags, a bit more flexible:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">
And here's the tag documentation.
If you are using following devices:
Samsung S3 GT-I9305 (Android 4.1.2)
Mac OS 10.6.8
Do following:
# echo "0x04e8" >> ~/.android/adb_usb.ini
# adb kill-server
# adb devices
(if you are not using Samsung device, change the Vendor ID "0x04e8" to the correct value of your Vendor)
If still not working, you may want to try following:
(1) On your Samsung device, disable "USB Debugging" and re-enable it again
(and try the adb commands again)
(2) Disconnect the USB cable, and re-connect it again
(3) Uninstall Samsung Kies
(4) Install Android File Transfer
(5) Reboot your Mac and the Samsung device
(6) Use hardware device to test your Android app
After getting the devices connected but you suddenly unplug the USB cable, and suppose now "adb devices" cannot see your device any more, even after "adb kill-server", in this case, you may want to try the following:
(1) power off your Mac
(2) disable "USB debuggine" on your Samsung device
(3) power off your Samsung device
(4) power on your Mac
(5) power on your Samsung device
(6) enable "USB debuggine" on your Samsung device
(7) connect the USB cable
(8) Run "adb devices"
(9) You should see the attached device now
when you bind localhost
or 127.0.0.1
, it means you can only connect to your service from local.
you cannot bind 10.0.0.1
because it not belong to you, you can only bind ip owned by your computer
you can bind 0.0.0.0
because it means all ip on your computer, so any ip can connect to your service if they can connect to any of your ip
I tested the following and it worked for me (in Swift):
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.blackColor().colorWithAlphaComponent(0.5).CGColor
UPDLOCK is used when you want to lock a row or rows during a select statement for a future update statement. The future update might be the very next statement in the transaction.
Other sessions can still see the data. They just cannot obtain locks that are incompatiable with the UPDLOCK and/or HOLDLOCK.
You use UPDLOCK when you wan to keep other sessions from changing the rows you have locked. It restricts their ability to update or delete locked rows.
You use HOLDLOCK when you want to keep other sessions from changing any of the data you are looking at. It restricts their ability to insert, update, or delete the rows you have locked. This allows you to run the query again and see the same results.
A string to char array is as simple as
String str = "someString";
char[] charArray = str.toCharArray();
Can you explain a little more on what you are trying to do?
* Update *
if I am understanding your new comment, you can use a byte array and example is provided.
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
With the following output
0x65 0x10 0xf3 0x29
Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,
large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.
-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs
Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.
Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples
react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.
kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).
Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools
OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.
The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO
DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.
Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.
Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.
Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.
PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.
qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).
Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community
jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.
angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).
DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.
Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.
The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM
Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.
CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.
ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.
Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.
CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.
Widgets - Demo Apps - Examples - GitHub
SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.
Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:
Wakanda Application Framework (datasource layer + browser-based interface widgets) that helps with browser and device compatibility across desktop and mobile
Wakanda is highly integrated, includes a ton of features out of the box, but has a very small GitHub community and SO presence.
Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.
SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.
Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework
Backbase - portal software
Shiny - front-end library on top R, with visualization, layout and control widgets
ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.
Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library
UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.
Height is easily implemented by recursion, take the maximum of the height of the subtrees plus one.
The "balance factor of R" refers to the right subtree of the tree which is out of balance, I suppose.
onblur fires when a field loses focus, while onchange fires when that field's value changes. These events will not always occur in the same order, however.
In Firefox, tabbing out of a changed field will fire onchange then onblur, and it will normally do the same in IE. However, if you press the enter key instead of tab, in Firefox it will fire onblur then onchange, while IE will usually fire in the original order. However, I've seen cases where IE will also fire blur first, so be careful. You can't assume that either the onblur or the onchange will happen before the other one.
If you want to append to the file, open it with 'a'
. If you want to seek through the file to find the place where you should insert the line, use 'r+'
. (docs)
Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.
The relevant paragraph:
Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.
This makes lots of sense.
For your specific question.. the o
in the <o:p>
means "Office namespace" so anything following the o:
in a tag means "I'm part of Office namespace" - in case of <o:p>
it just means paragraph, the equivalent of the ordinary <p>
tag.
I assume that every HTML tag has its Office "equivalent" and they have more.
There does not seem to be a straight-forward way provided by Google or Yahoo finance portals to download the full list of tickers. One possible 'brute force' way to get it is to query their APIs for every possible combinations of letters and save only those that return valid results. As silly as it may seem there are people who actually do it (ie. check this: http://investexcel.net/all-yahoo-finance-stock-tickers/).
You can download lists of symbols from exchanges directly or 3rd party websites as suggested by @Eugene S and @Capn Sparrow, however if you intend to use it to fetch data from Google or Yahoo, you have to sometimes use prefixes or suffixes to make sure that you're getting the correct data. This is because some symbols may repeat between exchanges, so Google and Yahoo prepend or append exchange codes to the tickers in order to distinguish between them. Here's an example:
Company: Vodafone
------------------
LSE symbol: VOD
in Google: LON:VOD
in Yahoo: VOD.L
NASDAQ symbol: VOD
in Google: NASDAQ:VOD
in Yahoo: VOD
In my case, This problem was caused by a mismatch in my Target framework setting under each project. When I created a new project, VS 2015 defaulted to 4.5.2, however all my nuget packages were built for 4.6.
For some reason, VS 2015 was not showing me these errors. I didn't see them until I created a new empty project and tried to add my nuget project there. This behavior may have been aggravated because I had renamed the project a few times during the initial setup.
I solved the problem by
There's also a C standard built-in library to get command line arguments: getopt
You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.
Not quite sure what the 300 is supposed to mean? Miss typo? However for iframes it would be best to use CSS :) - Ive found befor when importing youtube videos that it ignores inline things.
<style>
#myFrame { width:100%; height:100%; }
</style>
<iframe src="html_intro.asp" id="myFrame">
<p>Hi SOF</p>
</iframe>
If other whitespace characters are possible, then you'd want:
testString.split("\\s+");
You could either use the Google Guava library, which has implementations for Multi-Value-Maps (Apache Commons Collections has also implementations, but without generics).
However, if you don't want to use an external lib, then you would do something like this:
if (map.get(id) == null) { //gets the value for an id)
map.put(id, new ArrayList<String>()); //no ArrayList assigned, create new ArrayList
map.get(id).add(value); //adds value to list.
When making many plots, it makes sense to set it globally (relevant part is the second line, three lines together are a working example):
library('ggplot2')
theme_update(text = element_text(size=20))
ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point()
The instructions in @bsdnoobz answer are indeed helpful, but didn't get OpenCV to work on my system.
Apparently I needed to compile the library myself in order to get it to work, and not count on the pre-built binaries (which caused my programs to crash, probably due to incompatibility with my system).
I did get it to work, and wrote a comprehensive guide for compiling and installing OpenCV, and configuring Netbeans to work with it.
For completeness, it is also provided below.
When I first started using OpenCV, I encountered two major difficulties:
I read many tutorials and "how-to" articles, but none was really comprehensive and thorough. Eventually I succeeded in setting up the environment; and after a while of using this (great) library, I decided to write this small tutorial, which will hopefully help others.
The are three parts to this tutorial:
The environment I use is: Windows 7, OpenCV 2.4.0, Netbeans 7 and MinGW 3.20 (with compiler gcc 4.6.2).
Assumptions: You already have MinGW and Netbeans installed on your system.
When downloading OpenCV, the archive actually already contains pre-built binaries (compiled libraries and DLL's) in the 'build' folder. At first, I tried using those binaries, assuming somebody had already done the job of compiling for me. That didn't work.
Eventually I figured I have to compile the entire library on my own system in order for it to work properly.
Luckily, the compilation process is rather easy, thanks to CMake. CMake (stands for Cross-platform Make) is a tool which generates makefiles specific to your compiler and platform. We will use CMake in order to configure our building and compilation settings, generate a 'makefile', and then compile the library.
The steps are:
c:/opencv/
.c:/opencv/
.c:/opencv/release
.c:/opencv/release/
.mingw32-make
and press enter. This should start the compilation
process.C:/opencv/release/bin
to the system PATH. This will make sure our programs can find the
needed DLL's to run.Netbeans should be told where to find the header files and the compiled libraries (which were created in the previous section).
The header files are needed for two reasons: for compilation and for code completion. The compiled libraries are needed for the linking stage.
Note: In order for debugging to work, the OpenCV DLL's should be available, which is why we added the directory which contains them to the system PATH (previous section, step 5.4).
First, you should verify that Netbeans is configured correctly to work with
MinGW. Please see the screenshot below and verify your settings are correct
(considering paths changes according to your own installation). Also note
that the make
command should be from msys and not from Cygwin.
Next, for each new project you create in Netbeans, you should define the include path (the directory which contains the header files), the libraries path and the specific libraries you intend to use. Right-click the project name in the 'projects' pane, and choose 'properties'. Add the include path (modify the path according to your own installation):
Add the libraries path:
Add the specific libraries you intend to use. These libraries will be
dynamically linked to your program in the linking stage. Usually you will need
the core
library plus any other libraries according to the specific needs of
your program.
That's it, you are now ready to use OpenCV!
Here are the general steps you need to complete in order to install OpenCV and use it with Netbeans:
Here is a small example program which draws the text "Hello World : )" on a GUI window. You can use it to check that your installation works correctly. After compiling and running the program, you should see the following window:
#include "opencv2/opencv.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
int main(int argc, char** argv) {
//create a gui window:
namedWindow("Output",1);
//initialize a 120X350 matrix of black pixels:
Mat output = Mat::zeros( 120, 350, CV_8UC3 );
//write text on the matrix:
putText(output,
"Hello World :)",
cvPoint(15,70),
FONT_HERSHEY_PLAIN,
3,
cvScalar(0,255,0),
4);
//display the image:
imshow("Output", output);
//wait for the user to press any key:
waitKey(0);
return 0;
}
step 1 : Create a wrapper for the modal called clone-modal-wrapper
.
step 2 : Create a blank div called modal-wrapper
.
Step 3 : Copy the modal element from clone-modal-wrapper
to modal-wrapper
.
step 4 : Toggle the modal of modal-wrapper
.
<a data-toggle="modal" class='my-modal'>Open modal</a>
<div class="clone-modal-wrapper">
<div class='my-modal' class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Save"/>
</div>
</div>
</div>
</div>
</div>
<div class="modal-wrapper"></div>
$("a[data-target=#myModal]").click(function (e) {
e.preventDefault();
$(".modal-wrapper").html($(".clone-modal-wrapper").html());
$('.modal-wrapper').find('.my-modal').modal('toggle');
});
It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.
Other than that, I would suggest two things...
First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...
ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0
Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.
In my case, the file containing JSON string had BOM. Once I removed BOM the problem was solved.
Here is a generalized simple command argument interface you can paste to the top of all your scripts.
#!/bin/bash
declare -A flags
declare -A booleans
args=()
while [ "$1" ];
do
arg=$1
if [ "${1:0:1}" == "-" ]
then
shift
rev=$(echo "$arg" | rev)
if [ -z "$1" ] || [ "${1:0:1}" == "-" ] || [ "${rev:0:1}" == ":" ]
then
bool=$(echo ${arg:1} | sed s/://g)
booleans[$bool]=true
echo \"$bool\" is boolean
else
value=$1
flags[${arg:1}]=$value
shift
echo \"$arg\" is flag with value \"$value\"
fi
else
args+=("$arg")
shift
echo \"$arg\" is an arg
fi
done
echo -e "\n"
echo booleans: ${booleans[@]}
echo flags: ${flags[@]}
echo args: ${args[@]}
echo -e "\nBoolean types:\n\tPrecedes Flag(pf): ${booleans[pf]}\n\tFinal Arg(f): ${booleans[f]}\n\tColon Terminated(Ct): ${booleans[Ct]}\n\tNot Mentioned(nm): ${boolean[nm]}"
echo -e "\nFlag: myFlag => ${flags["myFlag"]}"
echo -e "\nArgs: one: ${args[0]}, two: ${args[1]}, three: ${args[2]}"
By running the command:
bashScript.sh firstArg -pf -myFlag "my flag value" secondArg -Ct: thirdArg -f
The output will be this:
"firstArg" is an arg
"pf" is boolean
"-myFlag" is flag with value "my flag value"
"secondArg" is an arg
"Ct" is boolean
"thirdArg" is an arg
"f" is boolean
booleans: true true true
flags: my flag value
args: firstArg secondArg thirdArg
Boolean types:
Precedes Flag(pf): true
Final Arg(f): true
Colon Terminated(Ct): true
Not Mentioned(nm):
Flag: myFlag => my flag value
Args: one => firstArg, two => secondArg, three => thirdArg
Basically, the arguments are divided up into flags booleans and generic arguments. By doing it this way a user can put the flags and booleans anywhere as long as he/she keeps the generic arguments (if there are any) in the specified order.
Allowing me and now you to never deal with bash argument parsing again!
You can view an updated script here
This has been enormously useful over the last year. It can now simulate scope by prefixing the variables with a scope parameter.
Just call the script like
replace() (
source $FUTIL_REL_DIR/commandParser.sh -scope ${FUNCNAME[0]} "$@"
echo ${replaceFlags[f]}
echo ${replaceBooleans[b]}
)
Doesn't look like I implemented argument scope, not sure why I guess I haven't needed it yet.
For Swift 5:
var attributes = [NSAttributedString.Key: AnyObject]()
attributes[.foregroundColor] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
For Swift 4:
var attributes = [NSAttributedStringKey: AnyObject]()
attributes[.foregroundColor] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
For Swift 3:
var attributes = [String: AnyObject]()
attributes[NSForegroundColorAttributeName] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
If you are looking to get a comma separated string into a column with CR LF you wont be able to do that in Notepad++, assuming you didn't want to write code, you could manipulate it in Microsoft Excel.
If you copy your string to location B1:
A2 =LEFT(B1,FIND(",",B1)-1)
B2 =MID(B1,FIND(",",B1)+1,10000)
Select A2 and B2, copy the code to successive cells (by dragging):
A3 =LEFT(B2,FIND(",",B2)-1)
B3 =MID(B2,FIND(",",B2)+1,10000)
When you get #VALUE! in the last cell of column A replace it with the previous rows B value.
In the end your A column will contain the desired text. Copy and past it anywhere you wish.
If a vector has N elements, there are N+1 possible answers for find. std::find and std::find_if return an iterator to the found element OR end() if no element is found. To change the code as little as possible, your find function should return the equivalent position:
size_t find( const vector<type>& where, int searchParameter )
{
for( size_t i = 0; i < where.size(); i++ ) {
if( conditionMet( where[i], searchParameter ) ) {
return i;
}
}
return where.size();
}
// caller:
const int position = find( firstVector, parameter );
if( position != secondVector.size() ) {
doAction( secondVector[position] );
}
I would still use std::find_if, though.
I had this, I added EXIT
and initially it didn't work, I guess per requiring the called program exiting
advice mentioned in another response here, however it now works without further ado - not sure what's caused this, but the point to note is that I'm calling a data file .html
rather than the program that handles it browser.exe
, I did not edit anything else but suffice it to say it's much neater just using a bat file to access the main access pages of those web documents and only having title.bat
, contents.bat
, index.bat
in the root folder with the rest of the content in a subfolder.
i.e.: contents.bat reads
cd subfolder
"contents.html"
exit
It also looks better if I change the bat file icons for just those items to suit the context they are in too, but that's another matter, hiding the bat files in the subfolder and creating custom icon shortcuts to them in the root folder with the images called for the customisation also hidden.
List constructor accepts any data structure that implements Collection interface to be used to build a list.
To get all the keys from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<String> keys = new ArrayList<>(map.keySet());
To get all the values from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<Integer> values = new ArrayList<>(map.values());
I made a method to do this below called jsonArrayToObjectList
. Its a handy static class that will take a filename and the file contains an array in JSON form.
List<Items> items = jsonArrayToObjectList(
"domain/ItemsArray.json", Item.class);
public static <T> List<T> jsonArrayToObjectList(String jsonFileName, Class<T> tClass) throws IOException {
ObjectMapper mapper = new ObjectMapper();
final File file = ResourceUtils.getFile("classpath:" + jsonFileName);
CollectionType listType = mapper.getTypeFactory()
.constructCollectionType(ArrayList.class, tClass);
List<T> ts = mapper.readValue(file, listType);
return ts;
}
if you do it from unix command (apart from PGAdmin) dont forget to pass the DB as a parameter. otherwise this extension will not be enabled when executing requests on this DB
psql -d -c "create EXTENSION pgcrypto;"
From android API Level 19, when I want to instance JSONArray object I put JSONObject directly as parameter like below:
JSONArray jsonArray=new JSONArray(jsonObject);
JSONArray has constructor to accept object.
Try to use getActivity();
This will solve your problem.
Can you do the string conversion while the List(of object) is being built? This would be the only way to avoid enumerating the whole list after the List(of object) was created.
As per my understanding you need to show 3 tables data in one html table using asp.net with c#.
I think best you just create one dataset with 3 DataTable object.
Bind that dataset to GriView directly on page load.
onclick="window.open('your_html', '_blank')"
You can also use numpy assuming if you are using python3.x here is an example
import numpy as np
x = 2.3
print(np.rint(x))
>>> 2.0
Simply use \1
instead of $1
:
In [1]: import re
In [2]: method = 'images/:id/huge'
In [3]: re.sub(r'(:[a-z]+)', r'<span>\1</span>', method)
Out[3]: 'images/<span>:id</span>/huge'
Also note the use of raw strings (r'...'
) for regular expressions. It is not mandatory but removes the need to escape backslashes, arguably making the code slightly more readable.
Another reason is that <u>
tags are deprecated in XHTML and HTML5, so it would need to produce something like <span style="text-decoration:underline">this</span>
. (IMHO, if <u>
is deprecated, so should be <b>
and <i>
.) Note that Markdown produces <strong>
and <em>
instead of <b>
and <i>
, respectively, which explains the purpose of the text therein instead of its formatting. Formatting should be handled by stylesheets.
Update:
The <u>
element is no longer deprecated in HTML5.
Interop with other languages founded on the DLR
is #1 reason I can think of. You can't pass them a Dictionary<string, object>
as it's not an IDynamicMetaObjectProvider
. Another added benefit is that it implements INotifyPropertyChanged
which means in the databinding world of WPF it also has added benefits beyond what Dictionary<K,V>
can provide you.
It's simpler if you pass an event parameter like this:
<a href="#" onclick="yes_js_login(event);">link</a>
function yes_js_login(e) {
e.stopImmediatePropagation();
}
OP wanted two specific maps, but if you'd like to have a dynamic number of maps on one page (for instance a list of retailer locations) you need to go another route. The standard implementation of Google maps API defines the map as a global variable, this won't work with a dynamic number of maps. Here's my code to solve this without global variables:
function mapAddress(mapElement, address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = {
zoom: 14,
center: results[0].geometry.location,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Just pass the ID and address of each map to the function to plot the map and mark the address.
Intent intent=new Intent(String) is defined for parameter task, whereas you are passing parameter componentname into this, use instead:
Intent i = new Intent(Settings.this, com.scytec.datamobile.vd.gui.android.AppPreferenceActivity.class);
startActivity(i);
In this statement replace ActivityName by Name of Class of Activity, this code resides in.
Try placing the host name (db01.mysql.vm.MyHostingServer.net
) in your windows host (C:\windows\system32\drivers\etc\host
) file along with it's IP address and port number and see if that helps.
Using an auxiliary Spannable Class as Android String Resources shares at the bottom of the webpage. You can approach this by creatingCharSquences
and giving them a style.
But in the example they give us, is just for bold, italic, and even colorize text. I needed to wrap several styles in aCharSequence
in order to set them in a TextView
. So to that Class (I named it CharSequenceStyles
) I just added this function.
public static CharSequence applyGroup(LinkedList<CharSequence> content){
SpannableStringBuilder text = new SpannableStringBuilder();
for (CharSequence item : content) {
text.append(item);
}
return text;
}
And in the view I added this.
message.push(postMessageText);
message.push(limitDebtAmount);
message.push(pretMessageText);
TextView.setText(CharSequenceStyles.applyGroup(message));
I hope this help you!
My favorite answer to this was posted by Chris Down at Unix & Linux Stack Exchange. I'll quote.
This is how the bash completion module for
make
gets its list:make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
It prints out a newline-delimited list of targets, without paging.
User Brainstone suggests piping to sort -u
to remove duplicate entries:
make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}' | sort -u
Source: How to list all targets in make? (Unix&Linux SE)
In conclusion, Here give more common way that include return value or void, and throw
import Foundation
extension NSObject {
func synchronized<T>(lockObj: AnyObject!, closure: () throws -> T) rethrows -> T
{
objc_sync_enter(lockObj)
defer {
objc_sync_exit(lockObj)
}
return try closure()
}
}
Just to note that nginx has now support for Websockets on the release 1.3.13. Example of use:
location /websocket/ {
proxy_pass ?http://backend_host;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400;
}
You can also check the nginx changelog and the WebSocket proxying documentation.
This error can come if there is validation error either in your wsdl or xsd file. For instance I too got the same issue while running wsdl2java to convert my wsdl file to generate the client. In one of my xsd it was defined as below
<xs:import schemaLocation="" namespace="http://MultiChoice.PaymentService/DataContracts" />
Where the schemaLocation was empty. By providing the proper data in schemaLocation resolved my problem.
<xs:import schemaLocation="multichoice.paymentservice.DataContracts.xsd" namespace="http://MultiChoice.PaymentService/DataContracts" />
I think it is better practice to keep your response under single control and for this reason I found out the most official solution.
response()->json([...])
->setStatusCode(Response::HTTP_OK, Response::$statusTexts[Response::HTTP_OK]);
add this after namespace
declaration:
use Illuminate\Http\Response;
The technique from Making something both a C identifier and a string? can be used here.
As usual with such preprocessor stuff, writing and understanding the preprocessor part can be hard, and includes passing macros to other macros and involves using # and ## operators, but using it is real easy. I find this style very useful for long enums, where maintaining the same list twice can be really troublesome.
enumFactory.h:
// expansion macro for enum value definition
#define ENUM_VALUE(name,assign) name assign,
// expansion macro for enum to string conversion
#define ENUM_CASE(name,assign) case name: return #name;
// expansion macro for string to enum conversion
#define ENUM_STRCMP(name,assign) if (!strcmp(str,#name)) return name;
/// declare the access function and define enum values
#define DECLARE_ENUM(EnumType,ENUM_DEF) \
enum EnumType { \
ENUM_DEF(ENUM_VALUE) \
}; \
const char *GetString(EnumType dummy); \
EnumType Get##EnumType##Value(const char *string); \
/// define the access function names
#define DEFINE_ENUM(EnumType,ENUM_DEF) \
const char *GetString(EnumType value) \
{ \
switch(value) \
{ \
ENUM_DEF(ENUM_CASE) \
default: return ""; /* handle input error */ \
} \
} \
EnumType Get##EnumType##Value(const char *str) \
{ \
ENUM_DEF(ENUM_STRCMP) \
return (EnumType)0; /* handle input error */ \
} \
someEnum.h:
#include "enumFactory.h"
#define SOME_ENUM(XX) \
XX(FirstValue,) \
XX(SecondValue,) \
XX(SomeOtherValue,=50) \
XX(OneMoreValue,=100) \
DECLARE_ENUM(SomeEnum,SOME_ENUM)
someEnum.cpp:
#include "someEnum.h"
DEFINE_ENUM(SomeEnum,SOME_ENUM)
The technique can be easily extended so that XX macros accepts more arguments, and you can also have prepared more macros to substitute for XX for different needs, similar to the three I have provided in this sample.
While this is similar to X-Macros others have mentioned, I think this solution is more elegant in that it does not require #undefing anything, which allows you to hide more of the complicated stuff is in the factory the header file - the header file is something you are not touching at all when you need to define a new enum, therefore new enum definition is a lot shorter and cleaner.
Be sure to include the $route service into your scope and do this:
$route.reload();
See this:
In your Page_Load you will want to clear out the normal output and write your own, for example:
string json = "{\"name\":\"Joe\"}";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
To convert a C# object to JSON you can use a library such as Json.NET.
Instead of getting your .aspx page to output JSON though, consider using a Web Service (asmx) or WCF, both of which can output JSON.
Webpack and Browserify do pretty much the same job, which is processing your code to be used in a target environment (mainly browser, though you can target other environments like Node). Result of such processing is one or more bundles - assembled scripts suitable for targeted environment.
For example, let's say you wrote ES6 code divided into modules and want to be able to run it in a browser. If those modules are Node modules, the browser won't understand them since they exist only in the Node environment. ES6 modules also won't work in older browsers like IE11. Moreover, you might have used experimental language features (ES next proposals) that browsers don't implement yet so running such script would just throw errors. Tools like Webpack and Browserify solve these problems by translating such code to a form a browser is able to execute. On top of that, they make it possible to apply a huge variety of optimisations on those bundles.
However, Webpack and Browserify differ in many ways, Webpack offers many tools by default (e.g. code splitting), while Browserify can do this only after downloading plugins but using both leads to very similar results. It comes down to personal preference (Webpack is trendier). Btw, Webpack is not a task runner, it is just processor of your files (it processes them by so called loaders and plugins) and it can be run (among other ways) by a task runner.
Webpack Dev Server provides a similar solution to Browsersync - a development server where you can deploy your app rapidly as you are working on it, and verify your development progress immediately, with the dev server automatically refreshing the browser on code changes or even propagating changed code to browser without reloading with so called hot module replacement.
I've been using Gulp for its conciseness and easy task writing, but have later found out I need neither Gulp nor Grunt at all. Everything I have ever needed could have been done using NPM scripts to run 3rd-party tools through their API. Choosing between Gulp, Grunt or NPM scripts depends on taste and experience of your team.
While tasks in Gulp or Grunt are easy to read even for people not so familiar with JS, it is yet another tool to require and learn and I personally prefer to narrow my dependencies and make things simple. On the other hand, replacing these tasks with the combination of NPM scripts and (propably JS) scripts which run those 3rd party tools (eg. Node script configuring and running rimraf for cleaning purposes) might be more challenging. But in the majority of cases, those three are equal in terms of their results.
As for the examples, I suggest you have a look at this React starter project, which shows you a nice combination of NPM and JS scripts covering the whole build and deploy process. You can find those NPM scripts in package.json
in the root folder, in a property named scripts
. There you will mostly encounter commands like babel-node tools/run start
. Babel-node is a CLI tool (not meant for production use), which at first compiles ES6 file tools/run
(run.js file located in tools) - basically a runner utility. This runner takes a function as an argument and executes it, which in this case is start
- another utility (start.js
) responsible for bundling source files (both client and server) and starting the application and development server (the dev server will be probably either Webpack Dev Server or Browsersync).
Speaking more precisely, start.js
creates both client and server side bundles, starts an express server and after a successful launch initializes Browser-sync, which at the time of writing looked like this (please refer to react starter project for the newest code).
const bs = Browsersync.create();
bs.init({
...(DEBUG ? {} : { notify: false, ui: false }),
proxy: {
target: host,
middleware: [wpMiddleware, ...hotMiddlewares],
},
// no need to watch '*.js' here, webpack will take care of it for us,
// including full page reloads if HMR won't work
files: ['build/content/**/*.*'],
}, resolve)
The important part is proxy.target
, where they set server address they want to proxy, which could be http://localhost:3000, and Browsersync starts a server listening on http://localhost:3001, where the generated assets are served with automatic change detection and hot module replacement. As you can see, there is another configuration property files
with individual files or patterns Browser-sync watches for changes and reloads the browser if some occur, but as the comment says, Webpack takes care of watching js sources by itself with HMR, so they cooperate there.
Now I don't have any equivalent example of such Grunt or Gulp configuration, but with Gulp (and somewhat similarly with Grunt) you would write individual tasks in gulpfile.js like
gulp.task('bundle', function() {
// bundling source files with some gulp plugins like gulp-webpack maybe
});
gulp.task('start', function() {
// starting server and stuff
});
where you would be doing essentially pretty much the same things as in the starter-kit, this time with task runner, which solves some problems for you, but presents its own issues and some difficulties during learning the usage, and as I say, the more dependencies you have, the more can go wrong. And that is the reason I like to get rid of such tools.
I imagine that trygetvalue is doing something more like:
if(myDict.ReallyOptimisedVersionofContains(someKey))
{
someVal = myDict[someKey];
return true;
}
return false;
So hopefully no try/catch anywhere.
I think it is just a method of convenience really. I generally use it as it saves a line of code or two.
The d3.js visualization examples I've been replicating on my local machine.. which import .JSON data.. all work fine on Mozilla Firefox browser; and on Chrome I get the cross-origins restrictions error. It's a weird thing how there's no issue with importing a local javascript file, but try loading a JSON and the browser gets nervous. There should at least be some setting to let the user over-ride it, the way pop-ups are blocked but I get to see an indication and a choice to unblock them.. no reason to be so Orwellian about the matter. Users shouldn't be treated as too naive to know what's best for them.
So I suggest using Firefox browser if you're working locally. And I hope people don't freak out over this and start bombing Mozilla to enforce cross-origin restrictions for local files.
On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:
yumdb search from_repo repoid
(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:
http://james.fedorapeople.org/yum/commands/find-repos-of-install.py
As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?
check pyplot
docs. For completeness,
import numpy as np
import matplotlib.pyplot as plt
#evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
public static Bitmap overlayBitmapToCenter(Bitmap bitmap1, Bitmap bitmap2) {
int bitmap1Width = bitmap1.getWidth();
int bitmap1Height = bitmap1.getHeight();
int bitmap2Width = bitmap2.getWidth();
int bitmap2Height = bitmap2.getHeight();
float marginLeft = (float) (bitmap1Width * 0.5 - bitmap2Width * 0.5);
float marginTop = (float) (bitmap1Height * 0.5 - bitmap2Height * 0.5);
Bitmap overlayBitmap = Bitmap.createBitmap(bitmap1Width, bitmap1Height, bitmap1.getConfig());
Canvas canvas = new Canvas(overlayBitmap);
canvas.drawBitmap(bitmap1, new Matrix(), null);
canvas.drawBitmap(bitmap2, marginLeft, marginTop, null);
return overlayBitmap;
}
You've told jQuery to expect a JSONP response, which is why jQuery has added the callback=jQuery16406345664265099913_1319854793396&_=1319854793399
part to the URL (you can see this in your dump of the request).
What you're returning is JSON, not JSONP. Your response looks like
{"red" : "#f00"}
and jQuery is expecting something like this:
jQuery16406345664265099913_1319854793396({"red" : "#f00"})
If you actually need to use JSONP to get around the same origin policy, then the server serving colors.json
needs to be able to actually return a JSONP response.
If the same origin policy isn't an issue for your application, then you just need to fix the dataType
in your jQuery.ajax
call to be json
instead of jsonp
.
Use ndindex
Sample array
arr = np.array([[1,4],
[2,3]])
print(arr)
...[[1,4],
[2,3]]
create an empty list to store the index and the element tuples
index_elements = []
for i in np.ndindex(arr.shape):
index_elements.append((arr[i],i))
convert the list of tuples into dictionary
index_elements = dict(index_elements)
The keys are the elements and the values are their indices - use keys to access the index
index_elements[4]
output
... (0,1)
The following works fine on my mac
sed -i.bak 's/foo/bar/g' sample
We are replacing foo with bar in sample file. Backup of original file will be saved in sample.bak
For editing inline without backup, use the following command
sed -i'' 's/foo/bar/g' sample
You can use the selectedIndex property to set it to the first option:
document.getElementById("select").selectedIndex = 0;
string[] fileEntries = Directory.GetFiles(directoryPath);
foreach (var file_name in fileEntries){
string fileName = file_name.Substring(directoryPath.Length + 1);
Console.WriteLine(fileName);
}
Personally I would use a const
reference. There is no need to increment the reference count just to decrement it again for the sake of a function call.
Algo in O(N)
count : 0;
if(str[0] == validChar ) :
count++;
else :
for i = 1 ; i < sizeOf(str) ; i++ :
if(str[i] == validChar AND str[i-1] != validChar)
count++;
end if;
end for;
end if;
return count;
This does almost everything you want:
f = open('data.txt', 'rb')
while True:
char = f.read(1)
if not char: break
print "{:02x}".format(ord(char)),
With data.txt created like this:
f = open('data.txt', 'wb')
f.write("ab\r\ncd")
f.close()
I get the following output:
61 62 0d 0a 63 64
tl;dr -- 1. You are using poor variable names. 2. You are slicing your hex strings incorrectly. 3. Your code is never going to replace any newlines. You may just want to forget about that feature. You do not quite yet understand the difference between a character, its integer code, and the hex string that represents the integer. They are all different: two are strings and one is an integer, and none of them are equal to each other. 4. For some files, you shouldn't remove newlines.
===
1. Your variable names are horrendous.
That's fine if you never want to ask anybody questions. But since every one needs to ask questions, you need to use descriptive variable names that anyone can understand. Your variable names are only slightly better than these:
fname = 'data.txt'
f = open(fname, 'rb')
xxxyxx = f.read()
xxyxxx = len(xxxyxx)
print "Length of file is", xxyxxx, "bytes. "
yxxxxx = 0
while yxxxxx < xxyxxx:
xyxxxx = hex(ord(xxxyxx[yxxxxx]))
xyxxxx = xyxxxx[-2:]
yxxxxx = yxxxxx + 1
xxxxxy = chr(13) + chr(10)
xxxxyx = str(xxxxxy)
xyxxxxx = str(xyxxxx)
xyxxxxx.replace(xxxxyx, ' ')
print xyxxxxx
That program runs fine, but it is impossible to understand.
2. The hex() function produces strings of different lengths.
For instance,
print hex(61)
print hex(15)
--output:--
0x3d
0xf
And taking the slice [-2:] for each of those strings gives you:
3d
xf
See how you got the 'x' in the second one? The slice:
[-2:]
says to go to the end of the string and back up two characters, then grab the rest of the string. Instead of doing that, take the slice starting 3 characters in from the beginning:
[2:]
3. Your code will never replace any newlines.
Suppose your file has these two consecutive characters:
"\r\n"
Now you read in the first character, "\r", and convert it to an integer, ord("\r"), giving you the integer 13. Now you convert that to a string, hex(13), which gives you the string "0xd"
, and you slice off the first two characters giving you:
"d"
Next, this line in your code:
bndtx.replace(entx, ' ')
tries to find every occurrence of the string "\r\n"
in the string "d"
and replace it. There is never going to be any replacement because the replacement string is two characters long and the string "d"
is one character long.
The replacement won't work for "\r\n"
and "0d"
either. But at least now there is a possibility it could work because both strings have two characters. Let's reduce both strings to a common denominator: ascii codes. The ascii code for "\r" is 13, and the ascii code for "\n" is 10. Now what about the string "0d"
? The ascii code for the character "0"
is 48, and the ascii code for the character "d" is 100. Those strings do not have a single character in common. Even this doesn't work:
x = '0d' + '0a'
x.replace("\r\n", " ")
print x
--output:--
'0d0a'
Nor will this:
x = 'd' + 'a'
x.replace("\r\n", " ")
print x
--output:--
da
The bottom line is: converting a character to an integer then to a hex string does not end up giving you the original character--they are just different strings. So if you do this:
char = "a"
code = ord(char)
hex_str = hex(code)
print char.replace(hex_str, " ")
...you can't expect "a" to be replaced by a space. If you examine the output here:
char = "a"
print repr(char)
code = ord(char)
print repr(code)
hex_str = hex(code)
print repr(hex_str)
print repr(
char.replace(hex_str, " ")
)
--output:--
'a'
97
'0x61'
'a'
You can see that 'a' is a string with one character in it, and '0x61'
is a string with 4 characters in it: '0'
, 'x'
, '6'
, and '1'
, and you can never find a four character string inside a one character string.
4) Removing newlines can corrupt the data.
For some files, you do not want to replace newlines. For instance, if you were reading in a .jpg file, which is a file that contains a bunch of integers representing colors in an image, and some colors in the image happened to be represented by the number 13 followed by the number 10, your code would eliminate those colors from the output.
However, if you are writing a program to read only text files, then replacing newlines is fine. But then, different operating systems use different newlines. You are trying to replace Windows newlines(\r\n), which means your program won't work on files created by a Mac or Linux computer, which use \n for newlines. There are easy ways to solve that, but maybe you don't want to worry about that just yet.
I hope all that's not too confusing.
I've installed Microsoft.ReportViewer.2012.Runtime nuget package and problem has been solved without installing ReportViewer.msi or sql feature pack 12
There are 2 main solutions:
The pure HTML one:
<input type="text" id="Textbox" name="Textbox" maxlength="10" />
The JavaScript one (attach it to a onKey Event):
function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
}
}
But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script.
for those who are using alphine linux, apk add openldap-dev
This a stab at creating a reusable column to comma separated string. In this case, I only one strings that have values and I do not want empty strings or nulls.
First I create a user defined type that is a one column table.
-- ================================
-- Create User-defined Table Type
-- ================================
USE [RSINET.MVC]
GO
-- Create the data type
CREATE TYPE [dbo].[SingleVarcharColumn] AS TABLE
(
data NVARCHAR(max)
)
GO
The real purpose of the type is to simplify creating a scalar function to put the column into comma separated values.
-- ================================================
-- Template generated from Template Explorer using:
-- Create Scalar Function (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Rob Peterson
-- Create date: 8-26-2015
-- Description: This will take a single varchar column and convert it to
-- comma separated values.
-- =============================================
CREATE FUNCTION fnGetCommaSeparatedString
(
-- Add the parameters for the function here
@column AS [dbo].[SingleVarcharColumn] READONLY
)
RETURNS VARCHAR(max)
AS
BEGIN
-- Declare the return variable here
DECLARE @result VARCHAR(MAX)
DECLARE @current VARCHAR(MAX)
DECLARE @counter INT
DECLARE @c CURSOR
SET @result = ''
SET @counter = 0
-- Add the T-SQL statements to compute the return value here
SET @c = CURSOR FAST_FORWARD
FOR SELECT COALESCE(data,'') FROM @column
OPEN @c
FETCH NEXT FROM @c
INTO @current
WHILE @@FETCH_STATUS = 0
BEGIN
IF @result <> '' AND @current <> '' SET @result = @result + ',' + @current
IF @result = '' AND @current <> '' SET @result = @current
FETCH NEXT FROM @c
INTO @current
END
CLOSE @c
DEALLOCATE @c
-- Return the result of the function
RETURN @result
END
GO
Now, to use this. I select the column I want to convert to a comma separated string into the SingleVarcharColumn Type.
DECLARE @s as SingleVarcharColumn
INSERT INTO @s VALUES ('rob')
INSERT INTO @s VALUES ('paul')
INSERT INTO @s VALUES ('james')
INSERT INTO @s VALUES (null)
INSERT INTO @s
SELECT iClientID FROM [dbo].tClient
SELECT [dbo].fnGetCommaSeparatedString(@s)
To get results like this.
rob,paul,james,1,9,10,11,12,13,14,15,16,18,19,23,26,27,28,29,30,31,32,34,35,36,37,38,39,40,41,42,44,45,46,47,48,49,50,52,53,54,56,57,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,81,82,83,84,87,88,90,91,92,93,94,98,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,120,121,122,123,124,125,126,127,128,129,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159
I made my data column in my SingleVarcharColumn type an NVARCHAR(MAX) which may hurt performance, but I flexibility was what I was looking for and it runs fast enough for my purposes. It would probably be faster if it were a varchar and if it had a fixed and smaller width, but I have not tested it.
With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.
Default parameters in JavaScript can be implemented in mainly two ways:
function myfunc(a, b)
{
// use this if you specifically want to know if b was passed
if (b === undefined) {
// b was not passed
}
// use this if you know that a truthy value comparison will be enough
if (b) {
// b was passed and has truthy value
} else {
// b was not passed or has falsy value
}
// use this to set b to a default value (using truthy comparison)
b = b || "default value";
}
The expression b || "default value"
evaluates the value AND existence of b
and returns the value of "default value"
if b
either doesn't exist or is falsy.
Alternative declaration:
function myfunc(a)
{
var b;
// use this to determine whether b was passed or not
if (arguments.length == 1) {
// b was not passed
} else {
b = arguments[1]; // take second argument
}
}
The special "array" arguments
is available inside the function; it contains all the arguments, starting from index 0
to N - 1
(where N
is the number of arguments passed).
This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!
Although undefined
is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:
b === void 0;
typeof b === 'undefined'; // also works for undeclared variables
You need to allow transaction to your DAO method. Add,
@Transactional(readOnly = true, propagation=Propagation.NOT_SUPPORTED)
over your dao methods.
And @Transactional
should be from the package:
org.springframework.transaction.annotation.Transactional
As an alternative to pathinfo()
, you can use
basename()
— Returns filename component of pathExample from PHP manual
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
You have to know the extension to remove it in advance though.
However, since your question suggests you have the need for getting the extension and the basename, I'd vote Pekka's answer as the most useful one, because it will give you any info you'd want about the path and file with one single native function.
Using python 3.6.3. Here after installing Jupyter through command 'python -m pip install jupyter', 'jupyter notebook' command didn't work for me using windows command prompt.
But, finally 'python -m notebook' did work and made jupyter notebook to run on local.
On a Windows machine I was able to log to to ssh from git bash with
ssh vagrant@VAGRANT_SERVER_IP
without providing a password
Using Bitvise SSH client on window
Server host: VAGRANT_SERVER_IP
Server port: 22
Username: vagrant
Password: vagrant
>>> import itertools
>>> int(''.join(itertools.takewhile(lambda s: s.isdigit(), string1)))
If the goal is to build an API that allow you to access your models in JSON format I recommend you to use the django-restframework
that is an enormously popular package within the Django community to achieve this type of tasks.
It include useful features such as Pagination, Defining Serializers, Nested models/relations and more. Even if you only want to do minor Javascript tasks and Ajax calls I would still suggest you to build a proper API using the Django Rest Framework instead of manually defining the JSON response.
Based on tips from https://developer.mozilla.org/en-US/docs/CSS/background-size I end up with the following recipe that worked for me
body {
overflow-y: hidden ! important;
overflow-x: hidden ! important;
background-color: #f8f8f8;
background-image: url('index.png');
/*background-size: cover;*/
background-size: contain;
background-repeat: no-repeat;
background-position: right;
}
You can use:
max(d, key = d.get)
# which is equivalent to
max(d, key = lambda k : d.get(k))
To return the key, value pair use:
max(d.items(), key = lambda k : k[1])
Here's another extension, this time in Scala.
customerQuery.getSingleOrNone match {
case Some(c) => // ...
case None => // ...
}
With this pimp:
import javax.persistence.{NonUniqueResultException, TypedQuery}
import scala.collection.JavaConversions._
object Implicits {
class RichTypedQuery[T](q: TypedQuery[T]) {
def getSingleOrNone : Option[T] = {
val results = q.setMaxResults(2).getResultList
if (results.isEmpty)
None
else if (results.size == 1)
Some(results.head)
else
throw new NonUniqueResultException()
}
}
implicit def query2RichQuery[T](q: TypedQuery[T]) = new RichTypedQuery[T](q)
}
MySQL create function syntax:
DELIMITER //
CREATE FUNCTION GETFULLNAME(fname CHAR(250),lname CHAR(250))
RETURNS CHAR(250)
BEGIN
DECLARE fullname CHAR(250);
SET fullname=CONCAT(fname,' ',lname);
RETURN fullname;
END //
DELIMITER ;
Use This Function In Your Query
SELECT a.*,GETFULLNAME(a.fname,a.lname) FROM namedbtbl as a
SELECT GETFULLNAME("Biswarup","Adhikari") as myname;
Watch this Video how to create mysql function and how to use in your query
I used .eslintrc.js and I have added following code.
module.exports = {
"parserOptions": {
"ecmaVersion": 6
}
};
int min = 65;
int max = 80;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
Note that nextInt(int max)
returns an int
between 0 inclusive and max exclusive. Hence the +1
.
I had the same problem, ensure that bootstrap.js is included in your html page. In my case the menu opened but did not close. As soon as I included the bootstrap js file, everything just worked.
Character sets will help out a ton here. You want to create a matching set for the characters that you want to validate:
\w
, which is the same as [A-Za-z0-9_]
in JavaScript (other languages can differ).-
and spaces, which can be combined into a matching set such as [\w\- ]
. However, you may want to consider using \s
instead of just the space character (\s
also matches tabs, and other forms of whitespace)
-
as \-
so that the regex engine doesn't confuse it with a character range like A-Z
^
and $
The full regex you're probably looking for is:
/^[\w\-\s]+$/
(Note that the +
indicates that there must be at least one character for it to match; use a *
instead, if a zero-length string is also ok)
Finally, http://www.regular-expressions.info/ is an awesome reference
Bonus Points: This regex does not match non-ASCII alphas. Unfortunately, the regex engine in most browsers does not support named character sets, but there are some libraries to help with that.
For languages/platforms that do support named character sets, you can use /^[\p{Letter}\d\_\-\s]+$/
DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";
// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");
Ref: http://www.csharp-examples.net/dataview-rowfilter/
http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx
var img;
for (var i = 0; i < jQuery('.MulImage').length; i++) {
var imgsrc = jQuery('.MulImage')[i];
var CurrentImgSrc = imgsrc.src;
img = jQuery('<img class="dynamic" style="width:100%;">');
img.attr('src', CurrentImgSrc);
jQuery('.YourDivClass').append(img);
}
I am very surprised that nobody here has mentioned the problem of connection and read timeout. It could happen (especially on Android and/or with some crappy network connectivity) that the request will hang and wait forever.
The following code (which also uses Apache IO Commons) takes this into account, and waits max. 5 seconds until it fails:
public static byte[] downloadFile(URL url)
{
try {
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.connect();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(conn.getInputStream(), baos);
return baos.toByteArray();
}
catch (IOException e)
{
// Log error and return null, some default or throw a runtime exception
}
}
>>> dict([('A', 1), ('B', 2), ('C', 3)])
{'A': 1, 'C': 3, 'B': 2}
It works for me. Please check if you are using the right imports?
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
I love the Shadow Wizard answer, which accually answers the question pretty nicelly. My jQuery twist on this which i use is here. http://jsfiddle.net/UJAe4/
After typing new value, the form is ready to send, just need to handle new values on the back end.
jQuery is:
(function ($)
{
$.fn.otherize = function (option_text, texts_placeholder_text) {
oSel = $(this);
option_id = oSel.attr('id') + '_other';
textbox_id = option_id + "_tb";
this.append("<option value='' id='" + option_id + "' class='otherize' >" + option_text + "</option>");
this.after("<input type='text' id='" + textbox_id + "' style='display: none; border-bottom: 1px solid black' placeholder='" + texts_placeholder_text + "'/>");
this.change(
function () {
oTbox = oSel.parent().children('#' + textbox_id);
oSel.children(':selected').hasClass('otherize') ? oTbox.show() : oTbox.hide();
});
$("#" + textbox_id).change(
function () {
$("#" + option_id).val($("#" + textbox_id).val());
});
};
}(jQuery));
So you apply this to the below html:
<form>
<select id="otherize_me">
<option value=1>option 1</option>
<option value=2>option 2</option>
<option value=3>option 3</option>
</select>
</form>
Just like this:
$(function () {
$("#otherize_me").otherize("other..", "put new option vallue here");
});
public ActionResult Index()
{
List<CustomerOrder_Result> obj = new List<CustomerOrder_Result>();
var orderlist = (from a in db.OrderMasters
join b in db.Customers on a.CustomerId equals b.Id
join c in db.CustomerAddresses on b.Id equals c.CustomerId
where a.Status == "Pending"
select new
{
Customername = b.Customername,
Phone = b.Phone,
OrderId = a.OrderId,
OrderDate = a.OrderDate,
NoOfItems = a.NoOfItems,
Order_amt = a.Order_amt,
dis_amt = a.Dis_amt,
net_amt = a.Net_amt,
status=a.Status,
address = c.address,
City = c.City,
State = c.State,
Pin = c.Pin
}) ;
foreach (var item in orderlist)
{
CustomerOrder_Result clr = new CustomerOrder_Result();
clr.Customername=item.Customername;
clr.Phone = item.Phone;
clr.OrderId = item.OrderId;
clr.OrderDate = item.OrderDate;
clr.NoOfItems = item.NoOfItems;
clr.Order_amt = item.Order_amt;
clr.net_amt = item.net_amt;
clr.address = item.address;
clr.City = item.City;
clr.State = item.State;
clr.Pin = item.Pin;
clr.status = item.status;
obj.Add(clr);
}
I've interpreted this question as:
"Can anyone tell me how to pass values for JavaScript for use in a JSP?"
If that's the case, this HTML file would pass a server-calculated variable to a JavaScript in a JSP.
<html>
<body>
<script type="text/javascript">
var serverInfo = "<%=getServletContext().getServerInfo()%>";
alert("Server information " + serverInfo);
</script>
</body>
</html>
Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.
Let me explain using step-by-step guidance.
First, download the source code from https://github.com/rmtheis/tess-two.
Import all three projects. After importing you will get an error.
To solve the error you have to create a res
folder in the tess-two project
First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"
After doing this in all three project the error should be gone.
Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.
Now you just need to import it into your workspace, but first you have to download android-ndk from this site:
http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file
Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable
Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture
done it
Now open cmd and go to on D:\Android Workspace\tess-two like below
If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:
Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest
Import test-two in this and run OCRTest and run it; you will get the best example of OCR.
Simpler variant of thelsdj's answer:
ls -tr | head -n -5 | xargs --no-run-if-empty rm
ls -tr displays all the files, oldest first (-t newest first, -r reverse).
head -n -5 displays all but the 5 last lines (ie the 5 newest files).
xargs rm calls rm for each selected file.
Better to support all the browsers:
img.lessOpacity {
opacity: 0.4;
filter: alpha(opacity=40);
zoom: 1; /* needed to trigger "hasLayout" in IE if no width or height is set */
}
You must fill the "Button" attribute of the "CompoundButton" class with a XML drawable path (my_checkbox). In the XML drawable, you must have :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="false" android:drawable="@drawable/checkbox_not_checked" />
<item android:state_checked="true" android:drawable="@drawable/checkbox_checked" />
<item android:drawable="@drawable/checkbox_not_checked" /> <!-- default -->
</selector>
Don't forget to replace my_checkbox by your filename of the checkbox drawable , checkbox_not_checked by your PNG drawable which is your checkbox when it's not checked and checkbox_checked with your image when it's checked.
For the size, directly update the layout parameters.
Put the background url in quotes.
It should be background: url('background.png');
See here for working demo.
You also have an issue with the background-repeat line
missing a semicolon in between two statements. If your background is really tiny you won't see it because of that issue.
Just to update on the solution, among the other issues, the background file was being refrenced with .../background.jpg
when it should have been ../background.jpg
(2 dots, not 3).
Using ddl.Items.Clear()
will clear the dropdownlist however you must be sure that your dropdownlist is not set to:
AppendDataBoundItems="True"
This option will cause the rebound data to be appended to the existing list which will NOT be cleared prior to binding.
SOLUTION
Add AppendDataBoundItems="False"
to your dropdownlist.
Now when data is rebound it will automatically clear all existing data beforehand.
Protected Sub ddl1_SelectedIndexChanged(sender As Object, e As EventArgs)
ddl2.DataSource = sql2
ddl2.DataBind()
End Sub
NOTE: This may not be suitable in all situations as appenddatbound items can cause your dropdown to append its own data on each change of the list.
TOP TIP
Still want a default list item adding to your dropdown but need to rebind data?
Use AppendDataBoundItems="False"
to prevent duplication data on postback and then directly after binding your dropdownlist insert a new default list item.
ddl.Items.Insert(0, New ListItem("Select ...", ""))
With the Material Components library you can customize the TextInputLayout
the hint text color using:
In the layout:
app:hintTextColor
attribute : the color of the label when it is collapsed and the text field is activeandroid:textColorHint
attribute: the color of the label in all other text field states (such as resting and disabled)Something like:
<com.google.android.material.textfield.TextInputLayout
app:hintTextColor="@color/mycolor"
android:textColorHint="@color/text_input_hint_selector"
.../>
If you are looking for range like function which works for float type, then here is a very good article.
def frange(start, stop, step=1.0):
''' "range()" like function which accept float type'''
i = start
while i < stop:
yield i
i += step
# Generate one element at a time.
# Preferred when you don't need all generated elements at the same time.
# This will save memory.
for i in frange(1.0, 2.0, 0.5):
print i # Use generated element.
# Generate all elements at once.
# Preferred when generated list ought to be small.
print list(frange(1.0, 10.0, 0.5))
Output:
1.0
1.5
[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]
I had this problem with git rebase -i origin/master
to a branch. I wanted to take master's version of the submodule ref, so I simply did:
git reset master path/to/submodule
and then
git rebase --continue
That solved the problem for me.
The following code downloads an image from a direct link to the disk into the project directory. Also note that it uses try-with-resources
.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FilenameUtils;
public class ImageDownloader
{
public static void main(String[] arguments) throws IOException
{
downloadImage("https://upload.wikimedia.org/wikipedia/commons/7/73/Lion_waiting_in_Namibia.jpg",
new File("").getAbsolutePath());
}
public static void downloadImage(String sourceUrl, String targetDirectory)
throws MalformedURLException, IOException, FileNotFoundException
{
URL imageUrl = new URL(sourceUrl);
try (InputStream imageReader = new BufferedInputStream(
imageUrl.openStream());
OutputStream imageWriter = new BufferedOutputStream(
new FileOutputStream(targetDirectory + File.separator
+ FilenameUtils.getName(sourceUrl)));)
{
int readByte;
while ((readByte = imageReader.read()) != -1)
{
imageWriter.write(readByte);
}
}
}
}
If you want to ALWAYS exclude certain properties for any class, you could use setMixInResolver
method:
@JsonIgnoreProperties({"id", "index", "version"})
abstract class MixIn {
}
mapper.setMixInResolver(new ClassIntrospector.MixInResolver(){
@Override
public Class<?> findMixInClassFor(Class<?> cls) {
return MixIn.class;
}
@Override
public ClassIntrospector.MixInResolver copy() {
return this;
}
});
I had this issue when running ng test
, so to fix it, I added to my xyz.component.spec.ts
file:
import { MatTableModule } from '@angular/material';
And added it to imports
section in TestBed.configureTestingModule({})
:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ ReactiveFormsModule, HttpClientModule, RouterTestingModule, MatTableModule ],
declarations: [ BookComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
.compileComponents();
}));
For MSSQL, there are two ways:(Consider you have a 'users' table,below both examples are using this table for example)
1) In case, you need to insert different values in users table. Then you can write statement like:
INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');
2) Another case, if you need to insert same value for all rows(for example, 10 rows you need to insert here). Then you can use below sample statement:
INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe')
GO 10
Hope this helps.
Or without (
and the need to escape it:
find . -not -name "*.exe" -not -name "*.dll"
and to also exclude the listing of directories
find . -not -name "*.exe" -not -name "*.dll" -not -type d
or in positive logic ;-)
find . -not -name "*.exe" -not -name "*.dll" -type f
I found it is better to use the command Serial.readString()
to replace the Serial.read()
to obtain the continuous I/O for Arduino.
One way can be to circularly store the values in the buffer array. and calculate average this way.
int j = (int) (counter % size);
buffer[j] = mostrecentvalue;
avg = (avg * size - buffer[j - 1 == -1 ? size - 1 : j - 1] + buffer[j]) / size;
counter++;
// buffer[j - 1 == -1 ? size - 1 : j - 1] is the oldest value stored
The whole thing runs in a loop where most recent value is dynamic.
I didn't want to have to have the YouTube app present on the device so I used this tutorial:
http://www.viralandroid.com/2015/09/how-to-embed-youtube-video-in-android-webview.html
...to produce this code in my app:
WebView mWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.video_webview);
mWebView=(WebView)findViewById(R.id.videoview);
//build your own src link with your video ID
String videoStr = "<html><body>Promo video<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
WebSettings ws = mWebView.getSettings();
ws.setJavaScriptEnabled(true);
mWebView.loadData(videoStr, "text/html", "utf-8");
}
//video_webview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:background="#000000"
android:id="@+id/bmp_programme_ll"
android:orientation="vertical" >
<WebView
android:id="@+id/videoview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
This worked just how I wanted it. It doesn't autoplay but the video streams within my app. Worth noting that some restricted videos won't play when embedded.
In C++ you are supposed to declare functions before you can use them. In your code integrate
is not declared before the point of the first call to integrate
. The same applies to sum
. Hence the error. Either reorder your definitions so that function definition precedes the first call to that function, or introduce a [forward] non-defining declaration for each function.
Additionally, defining external non-inline functions in header files in a no-no in C++. Your definitions of SkewNormalEvalutatable::SkewNormalEvalutatable
, getSkewNormal
, integrate
etc. have no business being in header file.
Also SkewNormalEvalutatable e();
declaration in C++ declares a function e
, not an object e
as you seem to assume. The simple SkewNormalEvalutatable e;
will declare an object initialized by default constructor.
Also, you receive the last parameter of integrate
(and of sum
) by value as an object of Evaluatable
type. That means that attempting to pass SkewNormalEvalutatable
as last argument of integrate
will result in SkewNormalEvalutatable
getting sliced to Evaluatable
. Polymorphism won't work because of that. If you want polymorphic behavior, you have to receive this parameter by reference or by pointer, but not by value.
Give this a go:
var distinct_list
= data.DATA.map(function (d) {return d[x];}).filter((v, i, a) => a.indexOf(v) === i)
I also came across this kind issue when re import old eclipse project. It occurred some old dependency as jar file in the project.
just remove
compile fileTree(dir: 'libs', include: '*.jar')
in gradle file
and add dependency in the gradle file.
It works for me ..
You can also use a Tuple<> for a strongly-typed grouping.
from grouping in list.GroupBy(x => new Tuple<string,string,string>(x.Person.LastName,x.Person.FirstName,x.Person.MiddleName))
select new SummaryItem
{
LastName = grouping.Key.Item1,
FirstName = grouping.Key.Item2,
MiddleName = grouping.Key.Item3,
DayCount = grouping.Count(),
AmountBilled = grouping.Sum(x => x.Rate),
}
The java instanceof
operator is used to test whether the object is an instance of the specified type (class or subclass or interface).
The instanceof in java is also known as type comparison operator
as it compares the instance with type. It returns either true
or false
. If we apply the instanceof
operator with any variable that has null
value, it returns false
.
From JDK 14+ which includes JEP 305 we can also do "Pattern Matching" for instanceof
Patterns basically test that a value has a certain type, and can extract information from the value when it has the matching type. Pattern matching allows a more clear and efficient expression of common logic in a system, namely the conditional removal of components from objects.
Before Java 14
if (obj instanceof String) {
String str = (String) obj; // need to declare and cast again the object
.. str.contains(..) ..
}else{
str = ....
}
Java 14 enhancements
if (!(obj instanceof String str)) {
.. str.contains(..) .. // no need to declare str object again with casting
} else {
.. str....
}
We can also combine the type check and other conditions together
if (obj instanceof String str && str.length() > 4) {.. str.contains(..) ..}
The use of pattern matching in instanceof
should reduce the overall number of explicit casts in Java programs.
PS: instanceOf
will only match when the object is not null, then only it can be assigned to str
.
Set the style on the textbox as text-transform: uppercase?
Bootstrap 4
$('.dropdown-menu[data-handledropdownclose="true"]').on("click.bs.dropdown", function (e) {
if ($(this).parent().hasClass("show")) {
var target = $(e.target);
if (!(target.hasClass("CloseDropDown") || target.parents(".CloseDropDown").length)) {
e.stopPropagation();
}
}
});
<div class="dropdown">
<button type="button" class="btn-no-border dropdown-toggle" data-toggle="dropdown">
<img src="~/Content/CSS/CssImages/Icons/usr_icon.png" alt="" title="language" class="float-right" />
</button>
<div class="dropdown-menu profile-menu-logout" data-handledropdownclose="true">
<div class="prof-name">
<i class="fa fa-user"></i> Hello World
</div>
<hr />
<div>
<a href="/Test/TestAction" class="CloseDropDown">
<i class="fa fa-briefcase"></i>
<span>Test Action</span>
</a>
</div>
<div>
<nav>
<ul class="nav-menu-prof padding-0">
<li class="menu-has-children">
<a href="#">
<span class="cyan-text-color">
Test 2
</span>
</a>
<ul id="ulList" class="padding-0 pad-left-25">
<li>
<a href="/Test/Test2" class="action currentmenu"> Test 1 </a>
<a href="/Test/Test2" class="action CloseDropDown"> Test 2 </a>
</li>
</ul>
</li>
</ul>
</nav>
</div>
<div>
<a href="/Account/Logout" class="cyan-text-color CloseDropDown">
<i class="fa fa-power-off"></i>
<span>Logout</span>
</a>
</div>
</div>
</div>
I had this error when trying to save an entity through JPA.
It was because I had a column with @JoinColumn
annotation that didn't have @ManyToOne
annotation.
Adding @ManyToOne
fixed the issue.
If you want to save it as .fig file, hgsave is the function in Matlab R2012a. In later versions, savefig may also work.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container,
false);
someClass.onCreate(rootView);
return rootView;
}
Keep an instance of my root view in my class
View view;
public void onCreate(View rootView) {
view = rootView;
Use the view to hide the keyboard
public void removePhoneKeypad() {
InputMethodManager inputManager = (InputMethodManager) view
.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
IBinder binder = view.getWindowToken();
inputManager.hideSoftInputFromWindow(binder,
InputMethodManager.HIDE_NOT_ALWAYS);
}
When you call a function, a new "namespace" is allocated on the stack. That's how functions can have local variables. As functions call functions, which in turn call functions, we keep allocating more and more space on the stack to maintain this deep hierarchy of namespaces.
To curb programs using massive amounts of stack space, a limit is usually put in place via ulimit -s
. If we remove that limit via ulimit -s unlimited
, our programs will be able to keep gobbling up RAM for their evergrowing stack until eventually the system runs out of memory entirely.
int eat_stack_space(void) { return eat_stack_space(); }
// If we compile this with no optimization and run it, our computer could crash.
Usually, using a ton of stack space is accidental or a symptom of very deep recursion that probably should not be relying so much on the stack. Thus the stack limit.
Impact on performace is minor but does exist. Using the time
command, I found that eliminating the stack limit increased performance by a few fractions of a second (at least on 64bit Ubuntu).
$http is a promise too, you can make it simpler:
return $q.all(tasks.map(function(d){
return $http.post('upload/tasks',d).then(someProcessCallback, onErrorCallback);
}));
From this forum:
parseInt()
returns primitive integer type (int), wherebyvalueOf
returns java.lang.Integer, which is the object representative of the integer. There are circumstances where you might want an Integer object, instead of primitive type.Of course, another obvious difference is that intValue is an instance method whereby parseInt is a static method.
I was having the same issue, it turns out one of the projects I was referencing was outside the solution directory (and therefore didn't share the same '/packages' folder). The solution that worked for me was to open the reference project's solution and build it there. Once that project built, the errors went away.
SQL Server has its own built in system for security that covers logins and roles. This is separate and parallel to Windows users and groups. You can use just SQL security and then all administration will occur within SQL server and there's no connection between those logins and the Windows users. If you use mixed mode then Windows users are treated just like SQL logins.
There are a number of features of each approach -
1) If you want to use connection pooling you have to use SQL logins, or all share the same windows user - not a good idea.
2) If you want to track what a particular user is doing, then using the windows authentication makes sense.
3) Using the windows tools to administer users is much more powerful than SQL, but the link between the two is tenuous, for instance if you remove a windows user then the related data within SQL isn't updated.
To get name of a Swift class from an object, e.g. for var object: SomeClass(), use
String(describing: type(of: object))
To get name of a Swift class from a class type, e.g. SomeClass, use:
String(describing: SomeClass.self)
Output:
"SomeClass"
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port