This worked for me Visual C++ Redistributable Packages
CPMSifDlg::EncodeAndSend()
method is declared as non-static
and thus it must be called using an object of CPMSifDlg
. e.g.
CPMSifDlg obj;
return obj.EncodeAndSend(firstName, lastName, roomNumber, userId, userFirstName, userLastName);
If EncodeAndSend
doesn't use/relate any specifics of an object (i.e. this
) but general for the class CPMSifDlg
then declare it as static
:
class CPMSifDlg {
...
static int EncodeAndSend(...);
^^^^^^
};
There is but one difference. You have to take care or name mangling win C++. But on windows you have to take care about 1) decrating the functions to be exported from the DLL 2) write a so called .def file which lists all the exported symbols.
In Windows while compiling a DLL have have to use
__declspec(dllexport)
but while using it you have to write __declspec(dllimport)
So the usual way of doing that is something like
#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif
The naming is a bit confusing, because it is often named EXPORT.. But that's what you'll find in most of the headers somwhere. So in your case you'd write (with the above #define)
int DLL_EXPORT add.... int DLL_EXPORT mult...
Remember that you have to add the Preprocessor directive BUILD_DLL during building the shared library.
Regards Friedrich
I think _naked might get what you want, but it also prevents the compiler from generating the stack management code for the function. extern "C" causes C style name decoration. Remove that and that should get rid of your _'s. The linker doesn't add the underscores, the compiler does. stdcall causes the argument stack size to be appended.
For more, see: http://en.wikipedia.org/wiki/X86_calling_conventions http://www.codeproject.com/KB/cpp/calling_conventions_demystified.aspx
The bigger question is why do you want to do that? What's wrong with the mangled names?
A simple comparison against string works:
<c:when test="${someModel.status == 'OLD'}">
I am also facing this kind of requirement.
From this discussion I got another Idea,
Obj.GetType().GetProperties()[0].Name
This is also showing the property name.
Obj.GetType().GetProperties().Count();
this showing number of properties.
Thanks to all. This is nice discussion.
To debug / inspect your rpm I suggest to use redline which is a java program
Usage :
java -cp redline-1.2.1-jar-with-dependencies.jar org.redline_rpm.Scanner foo.rpm
I had this same issue and it turned out to be an improper usage of an java API. I was initializing a builder in a batch processing method that was that not supposed to be initiallized more than once.
Basically I was doing something like:
for (batch in batches) {
process_batch(batch)
}
def process_batch(batch) {
var client = TransportClient.builder().build()
client.processList(batch)
}
when I should have done this:
for (batch in batches) {
var client = TransportClient.builder().build()
process_batch(batch, client)
}
def process_batch(batch, client) {
client.processList(batch)
}
To skip the first line just call:
next(inf)
Files in Python are iterators over lines.
It was windows permission issue i move the folder thats it inherit wrong permissions. When i move to wwwroot folder and add permission to iis user it start working fine.
To write text to (or read text from) the Windows clipboard use this VBA function:
Function Clipboard$(Optional s$)
Dim v: v = s 'Cast to variant for 64-bit VBA support
With CreateObject("htmlfile")
With .parentWindow.clipboardData
Select Case True
Case Len(s): .setData "text", v
Case Else: Clipboard = .getData("text")
End Select
End With
End With
End Function
'Three examples of copying text to the clipboard:
Clipboard "Excel Hero was here."
Clipboard var1 & vbLF & var2
Clipboard 123
'To read text from the clipboard:
MsgBox Clipboard
This is a solution that does NOT use MS Forms nor the Win32 API. Instead it uses the Microsoft HTML Object Library which is fast and ubiquitous and NOT deprecated by Microsoft like MS Forms. And this solution respects line feeds. This solution also works from 64-bit Office. Finally, this solution allows both writing to and reading from the Windows clipboard. No other solution on this page has these benefits.
I am using Windows 10 OS and GitHub Desktop version 1.0.9.
For the new Github For Windows, git.exe is present in the below location.
%LOCALAPPDATA%\GitHubDesktop\app-[gitdesktop-version]\resources\app\git\cmd\git.exe
Example:
%LOCALAPPDATA%\GitHubDesktop\app-1.0.9\resources\app\git\cmd
enum
type in Java 5 and onwards for the purpose you have described. It is type safe.If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.
Java 5 and up enum
type
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public String toString(){
return this.color;
}
}
If you wish to change the value of the enum you have created, provide a mutator method.
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public void setColor(String color){
this.color = color;
}
public String toString(){
return this.color;
}
}
Example of accessing:
public static void main(String args[]){
System.out.println(Color.RED.getColor());
// or
System.out.println(Color.GREEN);
}
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
Then, on JavaScript side, you can dynamically modify image's src
attribute with so-called Data URL.
document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..."
part) in the URL accordingly.
Similar Questions:
Your code can't find the figure or the name of your figure named the by error message. Solution:
import cv2
import numpy as np
import matplotlib.pyplot as plt
img=cv2.imread('??.jpg')#solution:img=cv2.imread('haha.jpg')
print(img)
The exponential function is e^x
where e
is a mathematical constant called Euler's number, approximately 2.718281
. This value has a close mathematical relationship with pi
and the slope of the curve e^x
is equal to its value at every point. np.exp()
calculates e^x
for each value of x
in your input array.
I got a similar failure with SMTP whenever my client machine changes network connection (e.g., home vs. office network) and somehow restarting network service (or rebooting the machine) resolves the issue for me. Not sure if this would apply to your case, but just in case.
sudo /etc/init.d/networking restart # for ubuntu
According the MDN custom headers are not exposed by default. The server admin need to expose them using "Access-Control-Expose-Headers" in the same fashion they deal with "access-control-allow-origin"
See this MDN link for confirmation [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers]
C does not and never has had a native string type. By convention, the language uses arrays of char
terminated with a null char, i.e., with '\0'
. Functions and macros in the language's standard libraries provide support for the null-terminated character arrays, e.g., strlen iterates over an array of char
until it encounters a '\0'
character and strcpy copies from the source string until it encounters a '\0'
.
The use of null-terminated strings in C reflects the fact that C was intended to be only a little more high-level than assembly language. Zero-terminated strings were already directly supported at that time in assembly language for the PDP-10 and PDP-11.
It is worth noting that this property of C strings leads to quite a few nasty buffer overrun bugs, including serious security flaws. For example, if you forget to null-terminate a character string passed as the source argument to strcpy
, the function will keep copying sequential bytes from whatever happens to be in memory past the end of the source string until it happens to encounter a 0
, potentially overwriting whatever valuable information follows the destination string's location in memory.
In your code example, the string literal "Hello, world!" will be compiled into a 14-byte long array of char
. The first 13 bytes will hold the letters, comma, space, and exclamation mark and the final byte will hold the null-terminator character '\0'
, automatically added for you by the compiler. If you were to access the array's last element, you would find it equal to 0
. E.g.:
const char foo[] = "Hello, world!";
assert(foo[12] == '!');
assert(foo[13] == '\0');
However, in your example, message
is only 10 bytes long. strcpy
is going to write all 14 bytes, including the null-terminator, into memory starting at the address of message
. The first 10 bytes will be written into the memory allocated on the stack for message
and the remaining four bytes will simply be written on to the end of the stack. The consequence of writing those four extra bytes onto the stack is hard to predict in this case (in this simple example, it might not hurt a thing), but in real-world code it usually leads to corrupted data or memory access violation errors.
You can write a simple readable solution to this by using both map
and filter
:
const nanoIndexes = Cars
.map((car, i) => car === 'Nano' ? i : -1)
.filter(index => index !== -1);
EDIT: If you don't need to support IE/Edge (or are transpiling your code), ES2019 gave us flatMap, which lets you do this in a simple one-liner:
const nanoIndexes = Cars.flatMap((car, i) => car === 'Nano' ? i : []);
The code below show you how to set ImageView from a url string, using RxAndroid. First, add RxAndroid library 2.0
dependencies {
// RxAndroid
compile 'io.reactivex.rxjava2:rxandroid:2.0.0'
compile 'io.reactivex.rxjava2:rxjava:2.0.0'
// Utilities
compile 'org.apache.commons:commons-lang3:3.5'
}
now use setImageFromUrl to set image.
public void setImageFromUrl(final ImageView imageView, final String urlString) {
Observable.just(urlString)
.filter(new Predicate<String>() {
@Override public boolean test(String url) throws Exception {
return StringUtils.isNotBlank(url);
}
})
.map(new Function<String, Drawable>() {
@Override public Drawable apply(String s) throws Exception {
URL url = null;
try {
url = new URL(s);
return Drawable.createFromStream((InputStream) url.getContent(), "profile");
} catch (final IOException ex) {
return null;
}
}
})
.filter(new Predicate<Drawable>() {
@Override public boolean test(Drawable drawable) throws Exception {
return drawable != null;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Drawable>() {
@Override public void accept(Drawable drawable) throws Exception {
imageView.setImageDrawable(drawable);
}
});
}
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
If you use JSON properly, you can have nested object without any issue :
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));
How about create a bat file, run the batch file before closing, and then close the current instance.
The batch file does this:
You can set FileAppender dynamically
SimpleLayout layout = new SimpleLayout();
FileAppender appender = new FileAppender(layout,"logname."+new Date().toLocaleString(),false);
logger.addAppender(appender);
Since Java 8, it seems like the java.time
standard library is the way to go. From Joda time web page:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Back to your question. Were you to use Java 8, I think you want LocalDateTime
. Because it contains the date and time-of-the-day, but is unaware of time zone or any reference point in time such as the unix epoch.
Comparator
provides a way for you to provide custom comparison logic for types that you have no control over.
Comparable
allows you to specify how objects that you are implementing get compared.
Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator
.
Otherwise you can use Comparable
.
If you want to delete manually (for me it was easier), follow this:
Let's get this example with "teste".
1 - First change the explorer to "project" and open "settings.gradle";
2 - Delete the module you want;
3 - Go to your root folder of your project and delete the module folder.
If you're using maven I would do something like this:
Being production your default profile:
<properties>
<activeProfile>production</activeProfile>
</properties>
And as an example of other profiles:
<profiles>
<!--Your default profile... selected if none specified-->
<profile>
<id>production</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<activeProfile>production</activeProfile>
</properties>
</profile>
<!--Profile 2-->
<profile>
<id>development</id>
<properties>
<activeProfile>development</activeProfile>
</properties>
</profile>
<!--Profile 3-->
<profile>
<id>otherprofile</id>
<properties>
<activeProfile>otherprofile</activeProfile>
</properties>
</profile>
<profiles>
In your application.properties you'll have to set:
spring.profiles.active=@activeProfile@
This works for me every time, hope it solves your problem.
There is an odd case I got in VS2017, about the space between ‘Any’ and 'CPU'. this is not about using command prompt.
If you have a build project file, which could call other solution files. You can try to add the space between Any and CPU, like this (the Platform property value):
<MSBuild Projects="@(SolutionToBuild2)" Properties ="Configuration=$(ProjectConfiguration);Platform=Any CPU;Rerun=$(MsBuildReRun);" />
Before I fix this build issue, it is like this (ProjectPlatform is a global variable, was set to 'AnyCPU'):
<MSBuild Projects="@(SolutionToBuild1)" Properties ="Configuration=$(ProjectConfiguration);Platform=$(ProjectPlatform);Rerun=$(MsBuildReRun);" />
Also, we have a lot projects being called using $ (ProjectPlatform), which is 'AnyCPU' and work fine. If we open proj file, we can see lines liket this and it make sense.
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
So my conclusion is, 'AnyCPU' works for calling project files, but not for calling solution files, for calling solution files, using 'Any CPU' (add the space.)
For now, I am not sure if it is a bug of VS project file or MSBuild. I am using VS2017 with VS2017 build tools installed.
For those who are newbie like me, Open IIS, expand your server name, choose sites, click on your website. On new install, it is Default web site. Click it. On the right side you have Default document option. Double click it. You will see default.htm, default.asp, index.htm etc.. to the extreme right click add. Enter the full name of your file(including extension) that you want to set it as default. click ok. Open cmd prompt as admin and reset iis. Remove all files from c:\inetpub\wwwroot folder like iisstart.html, index.html etc.
Note: This will automatically create web.config file in your c:\inetpub\wwwroot folder. I didnt have any web.config files in my inetpub or wwwroot folders. This automatically created one for me.
Next time when you enter http(s)://servername, it opens the default page you set.
You can use the stringr
library:
library('stringr')
a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A_C
# 6 0.55313288 f A_C
# 7 0.31264280 g A_C
# 8 0.33759921 h A_C
# 9 0.72322599 i A_C
# 10 0.25223075 j A_C
data$c <- str_replace_all(data$c, '_', '-')
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A-C
# 6 0.55313288 f A-C
# 7 0.31264280 g A-C
# 8 0.33759921 h A-C
# 9 0.72322599 i A-C
# 10 0.25223075 j A-C
Note that this does change factored variables into character.
//Do this
int IS_NULL_PTR(char *k){
memset(&k, k, sizeof k);
if(k) { return 71; } ;
return 72;
}
int PRINT_PTR_SAFE(char *KR){
char *E=KR;;
if (IS_NULL_PTR(KR)==71){
printf("%s\r\n",KR);
} else {
printf("%s","(null)\r\n");
}
}
int main(int argc,char *argv[]){
int i=0;
char *A=malloc(sizeof(char)*9);
;strcpy(A,"hello world");
for (i=((int)(A))-10;i<1e+40;i++){
PRINT_PTR_SAFE(i);
}
}
//Then watch the show!
//Edit as you wish. Just credit me if you really want more of this.
This is how I do it...
public class ThreadA {
public ThreadA(object[] args) {
...
}
public void Run() {
while (true) {
Thread.sleep(1000); // wait 1 second for something to happen.
doStuff();
if(conditionToExitReceived) // what im waiting for...
break;
}
//perform cleanup if there is any...
}
}
Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)
private void FireThread(){
Thread thread = new Thread(new ThreadStart(this.startThread));
thread.start();
}
private void (startThread){
new ThreadA(args).Run();
}
The thread is created by calling "FireThread()"
The newly created thread will run until its condition to stop is met, then it dies...
You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...
Best to read through : This MSDN Article
Paths under linux are separated by colons (:
), not semi-colons (;
), as theatrus correctly used it in his example. I believe Java respects this convention.
Alternatively to what andy suggested, you may use the following form (which sets CLASSPATH for the duration of the command):
CLASSPATH=".:../somejar.jar:../mysql-connector-java-5.1.6-bin.jar" java -Xmx500m ...
whichever is more convenient to you.
to get the smart break (break-word) work well on different browsers, what worked for me was the following set of rules:
#elm {
word-break:break-word; /* webkit/blink browsers */
word-wrap:break-word; /* ie */
}
-moz-document url-prefix() {/* catch ff */
#elm {
word-break: break-all; /* in ff- with no break-word we'll settle for break-all */
}
}
private String formatDate(String date, String inputFormat, String outputFormat) {
String newDate;
DateFormat inputDateFormat = new SimpleDateFormat(inputFormat);
inputDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputDateFormat = new SimpleDateFormat(outputFormat);
try {
newDate = outputDateFormat.format((inputDateFormat.parse(date)));
} catch (Exception e) {
newDate = "";
}
return newDate;
}
You'll need to create a plug-in. The documentation for CKEditor is very poor for this, especially since I believe it has changed significantly since FCKEditor. I would suggest copying an existing plug-in and studying it. A quick google for "CKEditor plugin" also found this blog post.
The default import method is already "relative", from the PYTHONPATH. The PYTHONPATH is by default, to some system libraries along with the folder of the original source file. If you run with -m to run a module, the current directory gets added to the PYTHONPATH. So if the entry point of your program is inside of Proj, then using import Common.Common
should work inside both Server.py and Client.py.
Don't do a relative import. It won't work how you want it to.
The canonical use case in e-commerce is credit card expiration dates, MM/yy. Subtract one second instead of one day. Otherwise the card will appear expired for the entire last day of the expiration month.
DateTime expiration = DateTime.Parse("07/2013");
DateTime endOfTheMonthExpiration = new DateTime(
expiration.Year, expiration.Month, 1).AddMonths(1).AddSeconds(-1);
When I ran into this problem, it was a result of trying to use an inner class to serve as the DO. Construction of the inner class (silently) required an instance of the enclosing class -- which wasn't available to Jackson.
In this case, moving the inner class to its own .java file fixed the problem.
As suggested in official docker document also. Try running this:
sudo vi /etc/apt/sources.list
Then remove/comment any (deb [arch=amd64] https://download.docker.com/linux/ubuntu/ xenial stable
) such entry at the last lines of the file.
Then in terminal run this command:
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu/ bionic stable"
sudo apt-get update
It worked in my case.
In Bootstrap 3 they do not have separate classes for different styles of labels.
http://getbootstrap.com/components/
However, you can customize bootstrap classes that way. In your css file
.lb-sm {
font-size: 12px;
}
.lb-md {
font-size: 16px;
}
.lb-lg {
font-size: 20px;
}
Alternatively, you can use header tags to change the sizes. For example, here is a medium sized label and a small-sized label
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<h3>Example heading <span class="label label-default">New</span></h3>_x000D_
<h6>Example heading <span class="label label-default">New</span></h6>
_x000D_
They might add size classes for labels in future Bootstrap versions.
On Options chapter, in the page you linked, you can see the backdrop
option. Passing this option with value 'static'
will prevent closing the modal.
As @PedroVagner pointed on comments, you also can pass {keyboard: false}
to prevent closing the modal by pressing Esc.
If you opening the modal by js use:
$('#myModal').modal({backdrop: 'static', keyboard: false})
If you are using data attributes, use:
<button data-target="#myModal" data-toggle="modal" data-backdrop="static" data-keyboard="false">
Launch demo modal
</button>`
there is a simple approach as below, you can use FromStream
method of an image to do the trick,
Just remember to use System.Drawing
;
// using image object not file
public byte[] imageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
function validatePhone(inputtxt) {_x000D_
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
return phoneno.test(inputtxt)_x000D_
}
_x000D_
The substitute command can be applied to a visual selection. Make a visual block over the lines that you want to change, and type :, and notice that the command-line is initialized like this: :'<,'>
. This means that the substitute command will operate on the visual selection, like so:
:'<,'>s/$/,/
And this is a substitution that should work for your example, assuming that you really want the comma at the end of each line as you've mentioned. If there are trailing spaces, then you may need to adjust the command accordingly:
:'<,'>s/\s*$/,/
This will replace any amount of whitespace preceding the end of the line with a comma, effectively removing trailing whitespace.
The same commands can operate on a range of lines, e.g. for the next 5 lines: :,+5s/$/,/
, or for the entire buffer: :%s/$/,/
.
It prints the byte
in Hexadecimal format.
No format string: 13
'X2' format string: 0D
http://msdn.microsoft.com/en-us/library/aa311428(v=vs.71).aspx
Check out the apache config files. For Debian/Ubuntu theyre in /etc/apache2/sites-available/
for RedHat/CentOS/etc they're in /etc/httpd/conf.d/
. If you've just installed it, the file in there is probably named default
.
Make sure that the config file in there is pointing to the correct folder and then make sure your scripts are located there.
The line you're looking for in those files is DocumentRoot /path/to/directory
.
For a blank install, your php files most likely needs to be in /var/www/
.
What you'll also need to do is find your php.ini file, probably located at /etc/php5/apache2/php.ini
or /etc/php.ini
and find the entry for display_errors
and switch it to On
.
Another cause is if the user's default database is unavailable.
I had an account that was used for backing up two databases. When the backup user's default database was taken off-line, the "no process on the other end of the pipe" error started.
Well you have to grab the client for that (surprise), you can either go the simple way:
var io = io.listen(server);
io.clients[sessionID].send()
Which may break, I doubt it, but it's always a possibility that io.clients
might get changed, so use the above with caution
Or you keep track of the clients yourself, therefore you add them to your own clients
object in the connection
listener and remove them in the disconnect
listener.
I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}}
might do the job.
When using React hooks there is no access to access to this.props.location
.
To capture url parameters use window
object.
const search = window.location.search;
const params = new URLSearchParams(search);
const foo = params.get('bar');
If you want to find the last populated cell in a particular column, the best method is:
Range("A" & Rows.Count).End(xlUp).Row
This code uses the very last cell in the entire column (65536 for Excel 2003, 1048576 in later versions), and then find the first populated cell above it. This has the ability to ignore "breaks" in your data and find the true last row.
IMO it's the different way to resolve a name from the OS and PHP.
Try:
echo gethostbyname("host.name.tld");
and
var_export (dns_get_record ( "host.name.tld") );
or
$dns=array("8.8.8.8","8.8.4.4");
var_export (dns_get_record ( "host.name.tld" , DNS_ALL , $dns ));
You should found some DNS/resolver error.
Building on the previous answer by @BadPirate, I experimented a bit further and came up with some clarifications/corrections. I found that layoutSubviews:
will be called on a view if and only if:
Some relevant details:
layoutSubviews:
is called whenever a UIScrollView scrolls, as it performs the scrolling by changing its bounds' origin.layoutSubviews:
when the view is eventually added to a view hierarchy.setNeedsLayout
, which sets/raises a flag. Each iteration of the run loop, for all views in the view hierarchy, this flag is checked. For each view where the flag is found raised, layoutSubviews:
is called on it and the flag is reset. Views higher up the hierarchy will be checked/called first.In vanilla Javascript/Angular you can do this like this:
scroll() {
let scroller = document.querySelector('.above-scroller');
let table = document.querySelector('.table');
table.scrollTo(scroller.scrollLeft,0);
}
HTML:
<div class="above-scroller" (scroll)="scroll()">
<div class="scroller"></div>
</div>
<div class="table" >
<table></table>
</div>
CSS:
.above-scroller {
overflow-x: scroll;
overflow-y:hidden;
height: 20px;
width: 1200px
}
.scroller {
width:4500px;
height: 20px;
}
.table {
width:100%;
height: 100%;
overflow: auto;
}
Since someone mentioned efficiency, I've benchmarked the functions given so far out of curiosity:
function startsWith1($str, $char) {
return strpos($str, $char) === 0;
}
function startsWith2($str, $char) {
return stripos($str, $char) === 0;
}
function startsWith3($str, $char) {
return substr($str, 0, 1) === $char;
}
function startsWith4($str, $char){
return $str[0] === $char;
}
function startsWith5($str, $char){
return (bool) preg_match('/^' . $char . '/', $str);
}
function startsWith6($str, $char) {
if (is_null($encoding)) $encoding = mb_internal_encoding();
return mb_substr($str, 0, mb_strlen($char, $encoding), $encoding) === $char;
}
Here are the results on my average DualCore machine with 100.000 runs each
// Testing '_string'
startsWith1 took 0.385906934738
startsWith2 took 0.457293987274
startsWith3 took 0.412894964218
startsWith4 took 0.366240024567 <-- fastest
startsWith5 took 0.642996072769
startsWith6 took 1.39859509468
// Tested "string"
startsWith1 took 0.384965896606
startsWith2 took 0.445554971695
startsWith3 took 0.42377281189
startsWith4 took 0.373164176941 <-- fastest
startsWith5 took 0.630424022675
startsWith6 took 1.40699005127
// Tested 1000 char random string [a-z0-9]
startsWith1 took 0.430691003799
startsWith2 took 4.447286129
startsWith3 took 0.413349866867
startsWith4 took 0.368592977524 <-- fastest
startsWith5 took 0.627470016479
startsWith6 took 1.40957403183
// Tested 1000 char random string [a-z0-9] with '_' prefix
startsWith1 took 0.384054899216
startsWith2 took 4.41522812843
startsWith3 took 0.408898115158
startsWith4 took 0.363884925842 <-- fastest
startsWith5 took 0.638479948044
startsWith6 took 1.41304707527
As you can see, treating the haystack as array to find out the char at the first position is always the fastest solution. It is also always performing at equal speed, regardless of string length. Using strpos
is faster than substr
for short strings but slower for long strings, when the string does not start with the prefix. The difference is irrelevant though. stripos
is incredibly slow with long strings. preg_match
performs mostly the same regardless of string length, but is only mediocre in speed. The mb_substr
solution performs worst, while probably being more reliable though.
Given that these numbers are for 100.000 runs, it should be obvious that we are talking about 0.0000x seconds per call. Picking one over the other for efficiency is a worthless micro-optimization, unless your app is doing startsWith
checking for a living.
I am using Parcellite and xsel
to copy last commit message from git
to my clipboard manager (for some reason xclip
does not work):
$ git log -1 --pretty=%B | xsel -i -b
I wasn't able to do that with any swal(sweatAlert) default callback function, so I forced with jquery, got the Ok button class inspecting the element in chrome an made something like this:
<script>
sweetAlert({
title:'Warning!',
text: 'Invalid user or password!',
type:'warning'
},function(isConfirm){
alert('ok');
});
$('.swal2-confirm').click(function(){
window.location.href = 'index.php';
});
</script>
The 'Ok' alert in function(isConfirm) was just a test to see if it would get into this function, if so I should be able to redirect from there, but I wasn't...
So I used jQuery to determine if the button "OK" of swal was clicked by getting it class: ".swal2-confirm' then I could redirect with success...
Hope this helps you all !
PS: I am using php echo to run the script, I din't have to leave php to run it, just use single quotes and you're done !
When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.
For docker on macOS, you can use docker-time-sync-agent. It works for me.
You can use the below code on your string and you will get the complete string without html part.
string title = "<b> Hulk Hogan's Celebrity Championship Wrestling <font color=\"#228b22\">[Proj # 206010]</font></b> (Reality Series, )".Replace(" ",string.Empty);
string s = Regex.Replace(title, "<.*?>", String.Empty);
here is the example using Pure JavaScript
function scrollpage() { _x000D_
function f() _x000D_
{_x000D_
window.scrollTo(0,i);_x000D_
if(status==0) {_x000D_
i=i+40;_x000D_
if(i>=Height){ status=1; } _x000D_
} else {_x000D_
i=i-40;_x000D_
if(i<=1){ status=0; } // if you don't want continue scroll then remove this line_x000D_
}_x000D_
setTimeout( f, 0.01 );_x000D_
}f();_x000D_
}_x000D_
var Height=document.documentElement.scrollHeight;_x000D_
var i=1,j=Height,status=0;_x000D_
scrollpage();_x000D_
</script>
_x000D_
<style type="text/css">_x000D_
_x000D_
#top { border: 1px solid black; height: 20000px; }_x000D_
#bottom { border: 1px solid red; }_x000D_
_x000D_
</style>
_x000D_
<div id="top">top</div>_x000D_
<div id="bottom">bottom</div>
_x000D_
You're getting None
because list.sort()
it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort()
without assigning it to a
again.
There is a built in function sorted()
, which returns a sorted version of the list - a = sorted(a)
will do what you want as well.
That because your csv file is in invalid format, maybe the line break in your text file is not the \n or \r
and, using c/c++ to parse text is not a good idea. try awk:
$awk -F"," '{print "ID="$1"\tName="$2"\tAge="$3"\tGender="$4}' 1.csv
ID=0 Name=Filipe Age=19 Gender=M
ID=1 Name=Maria Age=20 Gender=F
ID=2 Name=Walter Age=60 Gender=M
Written in Vanilla Javascript
//Get URL
var loc = window.location.href;
console.log(loc);
var index = loc.indexOf("?");
console.log(loc.substr(index+1));
var splitted = loc.substr(index+1).split('&');
console.log(splitted);
var paramObj = [];
for(var i=0;i<splitted.length;i++){
var params = splitted[i].split('=');
var key = params[0];
var value = params[1];
var obj = {
[key] : value
};
paramObj.push(obj);
}
console.log(paramObj);
//Loop through paramObj to get all the params in query string.
Simply:
Right click on your project.
Go to properties.
Select android (second option in the Left panel).
Click "add..." (in library), select your project.
Click ok.
And finally, clean your project.
If this doesn't work, make sure that "android-support-v7-appcompat
" is in your Project Explorer.
If it isn't there, you can add it by importing a simple project from: C:/android-sdks\extras\android\support\v7\appcompat
To call a SOAP web Service from android , try to use this client
DON'T FORGET TO ADD ksoap2-android.jar in your java build path
public class WsClient {
private static final String SOAP_ACTION = "somme";
private static final String OPERATION_NAME = "somme";
private static final String WSDL_TARGET_NAMESPACE = "http://example.ws";
private static final String SOAP_ADDRESS = "http://192.168.1.2:8080/axis2/services/Calculatrice?wsdl";
public String caclculerSomme() {
String res = null;
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME);
request.addProperty("a", "5");
request.addProperty("b", "2");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try {
httpTransport.call(SOAP_ACTION, envelope);
String result = envelope.getResponse().toString();
res = result;
System.out.println("############# resull is :" + result);
} catch (Exception exception) {
System.out.println("########### ERRER" + exception.getMessage());
}
return res;
}
}
All the error 80020101 means is that there was an error, of some sort, while evaluating JavaScript. If you load that JavaScript via Ajax, the evaluation process is particularly strict.
Sometimes removing // will fix the issue, but the inverse is not true... the issue is not always caused by //.
Look at the exact JavaScript being returned by your Ajax call and look for any issues in that script. For more details see a great writeup here
http://mattwhite.me/blog/2010/4/21/tracking-down-error-80020101-in-internet-exploder.html
You can get div content using .text()
in jquery
var divContent = $('#field-function_purpose').text();
console.log(divContent);
Managed to get the input field value by doing something like this:
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
username : ''
}
this.updateInput = this.updateInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
updateInput(event){
this.setState({username : event.target.value})
}
handleSubmit(){
console.log('Your input value is: ' + this.state.username)
//Send state to the server code
}
render(){
return (
<div>
<input type="text" onChange={this.updateInput}></input>
<input type="submit" onClick={this.handleSubmit} ></input>
</div>
);
}
}
//output
//Your input value is: x
You can also do the following. in your form class def:
max_number = forms.ChoiceField(widget = forms.Select(),
choices = ([('1','1'), ('2','2'),('3','3'), ]), initial='3', required = True,)
then when calling the form in your view you can dynamically set both initial choices and choice list.
yourFormInstance = YourFormClass()
yourFormInstance.fields['max_number'].choices = [(1,1),(2,2),(3,3)]
yourFormInstance.fields['max_number'].initial = [1]
Note: the initial values has to be a list and the choices has to be 2-tuples, in my example above i have a list of 2-tuples. Hope this helps.
To analyze two arrays (array1 and array2) they need to meet the following two requirements:
1) They need to be a numpy.ndarray
Check with
type(array1)
# and
type(array2)
If that is not the case for at least one of them perform
array1 = numpy.ndarray(array1)
# or
array2 = numpy.ndarray(array2)
2) The dimensions need to be as follows:
array1.shape #shall give (N, 1)
array2.shape #shall give (N,)
N is the number of items that are in the array. To provide array1 with the right number of axes perform:
array1 = array1[:, numpy.newaxis]
I faced the same error but i solved this by selecting invalidate caches/restart option.
Click
Is there a way to remove all previous click events that have been assigned to a button?
$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});
If you're positive that you will never use this code in a compiler that doesn't support it (Windows/VS, GCC, and Clang are examples of compilers that do support it), then you can certainly use #pragma once without worries.
You can also just use both (see example below), so that you get portability and compilation speedup on compatible systems
#pragma once
#ifndef _HEADER_H_
#define _HEADER_H_
...
#endif
I also needed a button to navigate left on a PageViewController, one that should do exactly what you would expect from the swipe motion.
Since I had a few rules already in place inside "pageViewController:viewControllerBeforeViewController" for dealing with the natural swipe navigation, I wanted the button to re-use all that code, and simply could not afford to use specific indexes to reach pages as the previous answers did. So, I had to take an alternate solution.
Please note that the following code is for a Page View Controller that is a property inside my custom ViewController, and has its spine set to mid.
Here is the code I wrote for my Navigate Left button:
- (IBAction)btnNavigateLeft_Click:(id)sender {
// Calling the PageViewController to obtain the current left page
UIViewController *currentLeftPage = [_pageController.viewControllers objectAtIndex:0];
// Creating future pages to be displayed
NSArray *newDisplayedPages = nil;
UIViewController *newRightPage = nil;
UIViewController *newLeftPage = nil;
// Calling the delegate to obtain previous pages
// My "pageViewController:viewControllerBeforeViewController" method returns nil if there is no such page (first page of the book).
newRightPage = [self pageViewController:_pageController viewControllerBeforeViewController:currentLeftPage];
if (newRightPage) {
newLeftPage = [self pageViewController:_pageController viewControllerBeforeViewController:newRightPage];
}
if (newLeftPage) {
newDisplayedPages = [[NSArray alloc] initWithObjects:newLeftPage, newRightPage, nil];
}
// If there are two new pages to display, show them with animation.
if (newDisplayedPages) {
[_pageController setViewControllers:newDisplayedPages direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:nil];
}
}
You can do something very similar to make a right navigation button from here.
cat *-text-file | grep -Eio "th[a-z]+"
There is no extra advantage for each of them. It totally depends on your scenario. Code below shows their difference.
Before inserts your html here
<div id="mainTabsDiv">
Prepend inserts your html here
<div id="homeTabDiv">
<span>
Home
</span>
</div>
<div id="aboutUsTabDiv">
<span>
About Us
</span>
</div>
<div id="contactUsTabDiv">
<span>
Contact Us
</span>
</div>
Append inserts your html here
</div>
After inserts your html here
When I try to cast data source from datagridview that used bindingsource it error accor cannot casting:
----------Solution------------
'I changed casting from bindingsource that bind with datagridview
'Code here
Dim dtdata As New DataTable()
dtdata = CType(bndsData.DataSource, DataTable)
The latest CRAN version of rJava will find the jvm.dll
automatically, without manually setting the PATH
or JAVA_HOME
. However note that:
C:\Program files\Java\
and the latter in C:\Program Files (x86)\Java\
so they do not conflict.As of Java version 9, support for x86 (win32) has been discontinued. Hence the latest working multi-arch setup is to install both jdk-8u172-windows-i586.exe and jdk-8u172-windows-x64.exe and then the binary package from CRAN:
install.packages("rJava")
The binary package from CRAN should pick up on the jvm by itself. Experts only: to build rJava from source, you need the --merge-multiarch
flag:
install.packages('rJava', type = 'source', INSTALL_opts='--merge-multiarch')
(Note: many of folks in other answers/comments have said to remove JAVA_HOME, so consider that. I have not revisited this issue recently to know if all the steps below are still necessary.)
Here is some quick advice on how to get up and running with R + rJava on Windows 7 64bit. There are several possibilities, but most have fatal flaws. Here is what worked for me:
Add jvm.dll to your PATH
rJava, the R<->Java bridge, will need jvm.dll, but R will have trouble finding that DLL. It resides in a folder like
C:\Program Files\Java\jdk1.6.0_25\jre\bin\server
or
C:\Program Files\Java\jre6\jre\bin\client
Wherever yours is, add that directory to your windows PATH variable. (Windows -> "Path" -> "Edit environment variables to for your account" -> PATH -> edit the value.)
You may already have Java on your PATH. If so you should find the client/server directory in the same Java "home" dir as the one already on your PATH.
To be safe, make sure your architectures match.If you have Java in Program Files
, it is 64-bit, so you ought to run R64. If you have Java in Program Files (x86)
, that's 32-bit, so you use plain 32-bit R.
Re-launch R from the Windows Menu
If R is running, quit.
From the Start Menu , Start R / RGUI, RStudio. This is very important, to make R pick up your PATH changes.
Install rJava 0.9.2.
Earlier versions do not work! Mirrors are not up-to-date, so go to the source at www.rforge.net: http://www.rforge.net/rJava/files/. Note the advice there
“Please use
`install.packages('rJava',,'http://www.rforge.net/')`
to install.”
That is almost correct. This actually works:
install.packages('rJava', .libPaths()[1], 'http://www.rforge.net/')
Watch the punctuation! The mysterious “.libPaths()[1],” just tells R to install the package in the primary library directory. For some reason, leaving the value blank doesn’t work, even though it should default.
Another code swift3
let myLabel = UILabel()
myLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
myLabel.center = CGPoint(x: 0, y: 0)
myLabel.textAlignment = .center
myLabel.text = "myLabel!!!!!"
self.view.addSubview(myLabel)
This is a slightly modified solution. The Process will be killed when it was idle for at least 1 second. Maybe you should add a timeof of X seconds and call the function from a separate thread.
private void SendToPrinter()
{
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.FileName = @"c:\output.pdf";
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process p = new Process();
p.StartInfo = info;
p.Start();
long ticks = -1;
while (ticks != p.TotalProcessorTime.Ticks)
{
ticks = p.TotalProcessorTime.Ticks;
Thread.Sleep(1000);
}
if (false == p.CloseMainWindow())
p.Kill();
}
If you mean VBA, then you can use FullName, for example:
strFileFullName = ThisWorkbook.FullName
(updated as considered by the comments: the former used ActiveWorkbook.FullName
could more likely be wrong, if other office files may be open(ed) and active. But in case you stored the macro in another file, as mentioned by user @user7296559 here, and really want the file name of the macro-using file, ActiveWorkbook
could be the correct choice, if it is guaranteed to be active at execution time.)
For Eclipse CDT Kepler what worked for me to get rid of std::thread
unresolved symbol is:
Go to Preferences->C/C++->Build->Settings
Select the Discovery tab
Select CDT GCC Built-in Compiler Settings [Shared]
Add the -std=c++11 to the "Command to get the compiler specs:" field such as:
${COMMAND} -E -P -v -dD -std=c++11 ${INPUTS}
Adding -std=c++11
to project Properties/C/C++ Build->Settings->Tool Settings->GCC C++ Compiler->Miscellaneous->Other
Flags wasn't enough for Kepler, however it was enough for older versions such as Helios.
I also hit this error. In my case the root cause was async related (during a codebase refactor): An asynchronous function that builds the object to which the "not a function" function belongs was not awaited, and the subsequent attempt to invoke the function throws the error, example below:
const car = carFactory.getCar();
car.drive() //throws TypeError: drive is not a function
The fix was:
const car = await carFactory.getCar();
car.drive()
Posting this incase it helps anyone else facing this error.
I had this problem only on Chrome.
I tried adding
var $ =jQuery.noConflict();
just before calling
$(document).ready(function () {
It worked.
Thanks a lot
You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME
The trim from jQuery is convenient if you are already using that framework.
$.trim(' your string ');
I tend to use jQuery often, so trimming strings with it is natural for me. But it's possible that there is backlash against jQuery out there? :)
you can't use aliases from select list inside the WHERE clause (because of the Order of Evaluation of a SELECT statement)
also you cannot use OVER
clause inside WHERE clause - "You can specify analytic functions with this clause in the select list or ORDER BY clause." (citation from docs.oracle.com)
select *
from (select
staff_id, site_id, pay_level, date,
max(date) over (partition by staff_id) max_date
from owner.table
where end_enrollment_date is null
)
where date = max_date
We can do this by the following way.
<link href="{{ asset('/css/style.css') }}" rel="stylesheet">
{{ HTML::style('css/style.css', array('media' => 'print')) }}
It will search the style file in the public folder of Laravel and then will render it.
To print a vector which possibly has complex numbers-
fprintf('Answer: %s\n', sprintf('%d ', num2str(x)));
git difftool tag/branch filename
For Sequelize 4
Query
SELECT * FROM Student WHERE LastName='Doe'
AND (FirstName = "John" or FirstName = "Jane") AND Age BETWEEN 18 AND 24
Syntax with Operators
const Op = require('Sequelize').Op;
var r = await to (Student.findAll(
{
where: {
LastName: "Doe",
FirstName: {
[Op.or]: ["John", "Jane"]
},
Age: {
// [Op.gt]: 18
[Op.between]: [18, 24]
}
}
}
));
Notes
$
(e.g $and
, $or
...){freezeTableName: true}
set in the table model then Sequelize will query against the plural form of its name ( Student -> Students )By using itemStateChanged(ItemListener)
you can track selecting and deselecting checkbox (and do whatever you want based on it):
myCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
//do something...
} else {//checkbox has been deselected
//do something...
};
}
});
Java Swing itemStateChanged docu should help too. By using isSelected()
method you can just test if actual is checkbox selected:
if(myCheckBox.isSelected()){_do_something_if_selected_}
I know it is an old question now, but for users who are using Maven
plugin with Eclipse
under Windows
, you have two options:
If you got Maven installed as a standalone application:
You can use the following command in the CMD
under your project
path:
mvn eclipse:eclipse
It will update your repository with all the missing jars, according
to your dependencies in your pom.xml
file.
If you haven't got Maven installed as a standalone application you can follow these steps on your eclipse:
Right click on the project
->Run As
-- >Run configurations
.
Then select mavenBuild
.
Then click new
button to create a configuration of the selected
type .Click on Browse workspace then select your project and in
goals specify eclipse:eclipse
You can refer to how to run the command mvn eclipse:eclipse for further details.
It is recommended to check default terminal shell before set JAVA_HOME environment variable, via following commands:
$ echo $SHELL
/bin/bash
If your default terminal is /bin/bash (Bash), then you should use @Adrian Petrescu method.
If your default terminal is /bin/zsh (Z Shell), then you should set these environment variable in ~/.zshenv file with following contents:
export JAVA_HOME="$(/usr/libexec/java_home)"
Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.
On the Developers bugs Facebook site, the last answer about that (parameters with sharer.php
), makes me believe it was a bug that was going to be resolved. Am I right?
https://developers.facebook.com/x/bugs/357750474364812/
Ibrahim Faour · · Facebook Platform Team
Apologies for the inconvenience. We aim to update our external reports as soon as we get a resolution on issues. I do understand that sometimes the answer provided may not be satisfying, but we are eager to keep our platform as stable and efficient as possible. Thanks!
I guess anther way, possibly faster, to achieve this is
1) Use dict comprehension to get desired dict (i.e., taking 2nd col of each array)
2) Then use pd.DataFrame
to create an instance directly from the dict without loop over each col and concat.
Assuming your mat
looks like this (you can ignore this since your mat
is loaded from file):
In [135]: mat = {'a': np.random.randint(5, size=(4,2)),
.....: 'b': np.random.randint(5, size=(4,2))}
In [136]: mat
Out[136]:
{'a': array([[2, 0],
[3, 4],
[0, 1],
[4, 2]]), 'b': array([[1, 0],
[1, 1],
[1, 0],
[2, 1]])}
Then you can do:
In [137]: df = pd.DataFrame ({name:mat[name][:,1] for name in mat})
In [138]: df
Out[138]:
a b
0 0 0
1 4 1
2 1 0
3 2 1
[4 rows x 2 columns]
No, you can use a StringWriter
to get rid of the intermediate MemoryStream
. However, to force it into XML you need to use a StringWriter
which overrides the Encoding
property:
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
Or if you're not using C# 6 yet:
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding { get { return Encoding.UTF8; } }
}
Then:
var serializer = new XmlSerializer(typeof(SomeSerializableObject));
string utf8;
using (StringWriter writer = new Utf8StringWriter())
{
serializer.Serialize(writer, entry);
utf8 = writer.ToString();
}
Obviously you can make Utf8StringWriter
into a more general class which accepts any encoding in its constructor - but in my experience UTF-8 is by far the most commonly required "custom" encoding for a StringWriter
:)
Now as Jon Hanna says, this will still be UTF-16 internally, but presumably you're going to pass it to something else at some point, to convert it into binary data... at that point you can use the above string, convert it into UTF-8 bytes, and all will be well - because the XML declaration will specify "utf-8" as the encoding.
EDIT: A short but complete example to show this working:
using System;
using System.Text;
using System.IO;
using System.Xml.Serialization;
public class Test
{
public int X { get; set; }
static void Main()
{
Test t = new Test();
var serializer = new XmlSerializer(typeof(Test));
string utf8;
using (StringWriter writer = new Utf8StringWriter())
{
serializer.Serialize(writer, t);
utf8 = writer.ToString();
}
Console.WriteLine(utf8);
}
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
}
Result:
<?xml version="1.0" encoding="utf-8"?>
<Test xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<X>0</X>
</Test>
Note the declared encoding of "utf-8" which is what we wanted, I believe.
You may also return to the previous state of the local repo in another way:
git add
. git reset --hard
.This will work for Bellow IE8 Versions
.lt-ie9 #yourID{
your css code
}
If you need ContainsAny with a specific StringComparison
(for example to ignore case) then you can use this String Extentions method.
public static class StringExtensions
{
public static bool ContainsAny(this string input, IEnumerable<string> containsKeywords, StringComparison comparisonType)
{
return containsKeywords.Any(keyword => input.IndexOf(keyword, comparisonType) >= 0);
}
}
Usage with StringComparison.CurrentCultureIgnoreCase
:
var input = "My STRING contains Many Substrings";
var substrings = new[] {"string", "many substrings", "not containing this string" };
input.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// The statement above returns true.
”xyz”.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// This statement returns false.
There are two models for implementing classes and instances in JavaScript: the prototyping way, and the closure way. Both have advantages and drawbacks, and there are plenty of extended variations. Many programmers and libraries have different approaches and class-handling utility functions to paper over some of the uglier parts of the language.
The result is that in mixed company you will have a mishmash of metaclasses, all behaving slightly differently. What's worse, most JavaScript tutorial material is terrible and serves up some kind of in-between compromise to cover all bases, leaving you very confused. (Probably the author is also confused. JavaScript's object model is very different to most programming languages, and in many places straight-up badly designed.)
Let's start with the prototype way. This is the most JavaScript-native you can get: there is a minimum of overhead code and instanceof will work with instances of this kind of object.
function Shape(x, y) {
this.x= x;
this.y= y;
}
We can add methods to the instance created by new Shape
by writing them to the prototype
lookup of this constructor function:
Shape.prototype.toString= function() {
return 'Shape at '+this.x+', '+this.y;
};
Now to subclass it, in as much as you can call what JavaScript does subclassing. We do that by completely replacing that weird magic prototype
property:
function Circle(x, y, r) {
Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords
this.r= r;
}
Circle.prototype= new Shape();
before adding methods to it:
Circle.prototype.toString= function() {
return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r;
}
This example will work and you will see code like it in many tutorials. But man, that new Shape()
is ugly: we're instantiating the base class even though no actual Shape is to be created. It happens to work in this simple case because JavaScript is so sloppy: it allows zero arguments to be passed in, in which case x
and y
become undefined
and are assigned to the prototype's this.x
and this.y
. If the constructor function were doing anything more complicated, it would fall flat on its face.
So what we need to do is find a way to create a prototype object which contains the methods and other members we want at a class level, without calling the base class's constructor function. To do this we are going to have to start writing helper code. This is the simplest approach I know of:
function subclassOf(base) {
_subclassOf.prototype= base.prototype;
return new _subclassOf();
}
function _subclassOf() {};
This transfers the base class's members in its prototype to a new constructor function which does nothing, then uses that constructor. Now we can write simply:
function Circle(x, y, r) {
Shape.call(this, x, y);
this.r= r;
}
Circle.prototype= subclassOf(Shape);
instead of the new Shape()
wrongness. We now have an acceptable set of primitives to built classes.
There are a few refinements and extensions we can consider under this model. For example here is a syntactical-sugar version:
Function.prototype.subclass= function(base) {
var c= Function.prototype.subclass.nonconstructor;
c.prototype= base.prototype;
this.prototype= new c();
};
Function.prototype.subclass.nonconstructor= function() {};
...
function Circle(x, y, r) {
Shape.call(this, x, y);
this.r= r;
}
Circle.subclass(Shape);
Either version has the drawback that the constructor function cannot be inherited, as it is in many languages. So even if your subclass adds nothing to the construction process, it must remember to call the base constructor with whatever arguments the base wanted. This can be slightly automated using apply
, but still you have to write out:
function Point() {
Shape.apply(this, arguments);
}
Point.subclass(Shape);
So a common extension is to break out the initialisation stuff into its own function rather than the constructor itself. This function can then inherit from the base just fine:
function Shape() { this._init.apply(this, arguments); }
Shape.prototype._init= function(x, y) {
this.x= x;
this.y= y;
};
function Point() { this._init.apply(this, arguments); }
Point.subclass(Shape);
// no need to write new initialiser for Point!
Now we've just got the same constructor function boilerplate for each class. Maybe we can move that out into its own helper function so we don't have to keep typing it, for example instead of Function.prototype.subclass
, turning it round and letting the base class's Function spit out subclasses:
Function.prototype.makeSubclass= function() {
function Class() {
if ('_init' in this)
this._init.apply(this, arguments);
}
Function.prototype.makeSubclass.nonconstructor.prototype= this.prototype;
Class.prototype= new Function.prototype.makeSubclass.nonconstructor();
return Class;
};
Function.prototype.makeSubclass.nonconstructor= function() {};
...
Shape= Object.makeSubclass();
Shape.prototype._init= function(x, y) {
this.x= x;
this.y= y;
};
Point= Shape.makeSubclass();
Circle= Shape.makeSubclass();
Circle.prototype._init= function(x, y, r) {
Shape.prototype._init.call(this, x, y);
this.r= r;
};
...which is starting to look a bit more like other languages, albeit with slightly clumsier syntax. You can sprinkle in a few extra features if you like. Maybe you want makeSubclass
to take and remember a class name and provide a default toString
using it. Maybe you want to make the constructor detect when it has accidentally been called without the new
operator (which would otherwise often result in very annoying debugging):
Function.prototype.makeSubclass= function() {
function Class() {
if (!(this instanceof Class))
throw('Constructor called without "new"');
...
Maybe you want to pass in all the new members and have makeSubclass
add them to the prototype, to save you having to write Class.prototype...
quite so much. A lot of class systems do that, eg:
Circle= Shape.makeSubclass({
_init: function(x, y, z) {
Shape.prototype._init.call(this, x, y);
this.r= r;
},
...
});
There are a lot of potential features you might consider desirable in an object system and no-one really agrees on one particular formula.
The closure way, then. This avoids the problems of JavaScript's prototype-based inheritance, by not using inheritance at all. Instead:
function Shape(x, y) {
var that= this;
this.x= x;
this.y= y;
this.toString= function() {
return 'Shape at '+that.x+', '+that.y;
};
}
function Circle(x, y, r) {
var that= this;
Shape.call(this, x, y);
this.r= r;
var _baseToString= this.toString;
this.toString= function() {
return 'Circular '+_baseToString(that)+' with radius '+that.r;
};
};
var mycircle= new Circle();
Now every single instance of Shape
will have its own copy of the toString
method (and any other methods or other class members we add).
The bad thing about every instance having its own copy of each class member is that it's less efficient. If you are dealing with large numbers of subclassed instances, prototypical inheritance may serve you better. Also calling a method of the base class is slightly annoying as you can see: we have to remember what the method was before the subclass constructor overwrote it, or it gets lost.
[Also because there is no inheritance here, the instanceof
operator won't work; you would have to provide your own mechanism for class-sniffing if you need it. Whilst you could fiddle the prototype objects in a similar way as with prototype inheritance, it's a bit tricky and not really worth it just to get instanceof
working.]
The good thing about every instance having its own method is that the method may then be bound to the specific instance that owns it. This is useful because of JavaScript's weird way of binding this
in method calls, which has the upshot that if you detach a method from its owner:
var ts= mycircle.toString;
alert(ts());
then this
inside the method won't be the Circle instance as expected (it'll actually be the global window
object, causing widespread debugging woe). In reality this typically happens when a method is taken and assigned to a setTimeout
, onclick
or EventListener
in general.
With the prototype way, you have to include a closure for every such assignment:
setTimeout(function() {
mycircle.move(1, 1);
}, 1000);
or, in the future (or now if you hack Function.prototype) you can also do it with function.bind()
:
setTimeout(mycircle.move.bind(mycircle, 1, 1), 1000);
if your instances are done the closure way, the binding is done for free by the closure over the instance variable (usually called that
or self
, though personally I would advise against the latter as self
already has another, different meaning in JavaScript). You don't get the arguments 1, 1
in the above snippet for free though, so you would still need another closure or a bind()
if you need to do that.
There are lots of variants on the closure method too. You may prefer to omit this
completely, creating a new that
and returning it instead of using the new
operator:
function Shape(x, y) {
var that= {};
that.x= x;
that.y= y;
that.toString= function() {
return 'Shape at '+that.x+', '+that.y;
};
return that;
}
function Circle(x, y, r) {
var that= Shape(x, y);
that.r= r;
var _baseToString= that.toString;
that.toString= function() {
return 'Circular '+_baseToString(that)+' with radius '+r;
};
return that;
};
var mycircle= Circle(); // you can include `new` if you want but it won't do anything
Which way is “proper”? Both. Which is “best”? That depends on your situation. FWIW I tend towards prototyping for real JavaScript inheritance when I'm doing strongly OO stuff, and closures for simple throwaway page effects.
But both ways are quite counter-intuitive to most programmers. Both have many potential messy variations. You will meet both (as well as many in-between and generally broken schemes) if you use other people's code/libraries. There is no one generally-accepted answer. Welcome to the wonderful world of JavaScript objects.
[This has been part 94 of Why JavaScript Is Not My Favourite Programming Language.]
LATEST UPDATE:
Use the official version from jCenter instead.
dependencies {
compile 'com.android.volley:volley:1.0.0'
}
The dependencies below points to deprecated volley that is no longer maintained.
ORIGINAL ANSWER
You can use this in dependency section of your build.gradle file to use volley
dependencies {
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}
UPDATED:
Its not official but a mirror copy of official Volley. It is regularly synced and updated with official Volley Repository so you can go ahead to use it without any worry.
Use stash; like this:
git add .
git reset Files/I/Want/To/Keep
git stash --keep-index
git commit -a -m "Done!"
git stash pop
If you accidentally commit a file, and want to rewrite your git history, use:
git reset HEAD~1 path/to/file
git commit -a -m "rollback"
git rebase -i HEAD~2
and squash to the two leading commits. You can write a helper script to do either of these if you have a known set of files you prefer not to automatically commit.
I had the same problem. mysql -u root -p
worked for me. It later asks you for a password. You should then enter the password that you had set for mysql. The default password could be password
, if you did not set one. More info here.
du -sh [file_name]
works perfectly to get size of a particular file.
My solution was that I had recently upgraded my iOS device to 8.3 and Xcode still didn't recognize it. The fix was to simply upgrade Xcode to 6.3 :)
.imgContainer {
overflow: hidden;
width: 200px;
height: 100px;
}
.imgContainer img {
width: 200px;
height: 120px;
}
<div class="imgContainer">
<img src="imageSrc" />
</div>
The containing div with essentially crop the image by hiding the overflow.
I just wanted to add that if you don't see Team -> Share project, it's likely you have to remove the project from the workspace before importing it back in. This is what happened to me, and I had to remove and readd it to the workspace for it to fix itself. (This happened when moving from dramatically different Eclipse versions + plugins using the same workspace.)
subclipse not showing "share project" option on project context menu in eclipse
Use this code is whork :
if (!preg_match('#^http(s)?://#', $url)) {
$url = 'http://' . $url;
}
$urlParts = parse_url($url);
$url = preg_replace('/^www\./', '', $urlParts['host']);
A better solution would be using Kendo ui draw dom to export to pdf-
Suppose the following html file which contains the canvas tag:
<script src="http://kendo.cdn.telerik.com/2017.2.621/js/kendo.all.min.js"></script>
<script type="x/kendo-template" id="page-template">
<div class="page-template">
<div class="header">
</div>
<div class="footer" style="text-align: center">
<h2> #:pageNum# </h2>
</div>
</div>
</script>
<canvas id="myCanvas" width="500" height="500"></canvas>
<button onclick="ExportPdf()">download</button>
Now after that in your script write down the following and it will be done:
function ExportPdf(){
kendo.drawing
.drawDOM("#myCanvas",
{
forcePageBreak: ".page-break",
paperSize: "A4",
margin: { top: "1cm", bottom: "1cm" },
scale: 0.8,
height: 500,
template: $("#page-template").html(),
keepTogether: ".prevent-split"
})
.then(function(group){
kendo.drawing.pdf.saveAs(group, "Exported_Itinerary.pdf")
});
}
And that is it, Write anything in that canvas and simply press that download button all exported into PDF. Here is a link to Kendo UI - http://docs.telerik.com/kendo-ui/framework/drawing/drawing-dom And a blog to better understand the whole process - https://www.cronj.com/blog/export-htmlcss-pdf-using-javascript/
You could also set the default format for float :
pd.options.display.float_format = '{:.2%}'.format
Use '{:.2%}' instead of '{:.2f}%' - The former converts 0.41 to 41.00% (correctly), the latter to 0.41% (incorrectly)
I was facing this same case today, I had to download a pdf file as an attachment (the file shouldn't be rendered in the browser, but downloaded instead). To achieve that I discovered I had to get the file in an Angular Blob
, and, at the same time, add a Content-Disposition
header in the response.
This was the simplest I could get (Angular 7):
Inside the service:
getFile(id: String): Observable<HttpResponse<Blob>> {
return this.http.get(`./file/${id}`, {responseType: 'blob', observe: 'response'});
}
Then, when I need to download the file in a component, I can simply:
fileService.getFile('123').subscribe((file: HttpResponse<Blob>) => window.location.href = file.url);
UPDATE:
Removed unnecessary header setting from service
{ "date" : "1000000" }
in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }
It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback)
and if that works, you have a typing issue.
The distinction between reference types and value types are basically a performance tradeoff in the design of the language. Reference types have some overhead on construction and destruction and garbage collection, because they are created on the heap. Value types on the other hand have overhead on method calls (if the data size is larger than a pointer), because the whole object is copied rather than just a pointer. Because strings can be (and typically are) much larger than the size of a pointer, they are designed as reference types. Also, as Servy pointed out, the size of a value type must be known at compile time, which is not always the case for strings.
The question of mutability is a separate issue. Both reference types and value types can be either mutable or immutable. Value types are typically immutable though, since the semantics for mutable value types can be confusing.
Reference types are generally mutable, but can be designed as immutable if it makes sense. Strings are defined as immutable because it makes certain optimizations possible. For example, if the same string literal occurs multiple times in the same program (which is quite common), the compiler can reuse the same object.
So why is "==" overloaded to compare strings by text? Because it is the most useful semantics. If two strings are equal by text, they may or may not be the same object reference due to the optimizations. So comparing references are pretty useless, while comparing text are almost always what you want.
Speaking more generally, Strings has what is termed value semantics. This is a more general concept than value types, which is a C# specific implementation detail. Value types have value semantics, but reference types may also have value semantics. When a type have value semantics, you can't really tell if the underlying implementation is a reference type or value type, so you can consider that an implementation detail.
I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json)
. my_json_object
in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.
The way I ended up solving it: the write_to_file.json
will have everything up to the bytes object that is causing the issue.
In my particular case this was a line obtained through
for line in text:
json_object['line'] = line.strip()
I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:
for line in text:
json_object['line'] = line.strip().decode()
Here's another variation I've used when wanting to generate a script tag inline (so it executes immediately) without needing any form of escapes:
<script>
var script = document.createElement('script');
script.src = '/path/to/script.js';
document.write(script.outerHTML);
</script>
(Note: contrary to most examples on the net, I'm not setting type="text/javascript"
on neither the enclosing tag, nor the generated one: there is no browser not having that as the default, and so it is redundant, but will not hurt either, if you disagree).
For me both answers worked.
<Context docBase="/tmp/wars/hpong" path="" reloadable="true" />
<Service name="Catalina2"> <Connector port="8070" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8743" /> <Engine name="Catalina2" defaultHost="localhost"> <Host name="localhost" unpackWARs="true" autoDeploy="true"> <Context path="" docBase="/tmp/wars/hpong" reloadable="true"> <WatchedResource>WEB-INF/web.xml</WatchedResource> </Context> </Host> </Engine> </Service>
Note: when you declare docBase under context then ignore appBase at Host.
ROOT.war
and place it under webapps. So now unmatched url requests from other wars(contextpaths) will land into this war. This is better way to handle ROOT ("/**") context path. The second option is (double) loading the wars from Webapps folder as well. Also it only needs uncompressed war folder which is a headache.
As mentioned in a comment above, you can have expressions within the template strings/literals. Example:
const one = 1;_x000D_
const two = 2;_x000D_
const result = `One add two is ${one + two}`;_x000D_
console.log(result); // output: One add two is 3
_x000D_
GlobalStrings.AddRange(localStrings);
Note: You cannot declare the list object using the interface (IList).
Documentation: List<T>.AddRange(IEnumerable<T>)
.
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
The following configs works on Cent OS 6 or earlier
As stated above first have to disable selinux.
Step 1 nano /etc/sysconfig/selinux
Make sure the file has this configurations
SELINUX=disabled
SELINUXTYPE=targeted
Then restart the system
Step 2
iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT
Step 3
sudo service iptables save
For Cent OS 7
step 1
firewall-cmd --zone=public --permanent --add-port=8080/tcp
Step 2
firewall-cmd --reload
There is no native boolean data type for SQLite. Per the Datatypes doc:
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).
The to_yaml
method seems to be useful sometimes:
$foo = {:name => "Clem", :age => 43}
puts $foo.to_yaml
returns
---
:age: 43
:name: Clem
(Does this depend on some YAML
module being loaded? Or would that typically be available?)
I had the same problem, getting the message "ImportError: No module named numpy".
I'm also using anaconda and found out that I needed to add numpy to the ENV I was using. You can check the packages you have in your environment with the command:
conda list
So, when I used that command, numpy was not displayed. If that is your case, you just have to add it, with the command:
conda install numpy
After I did that, the error with the import numpy
was gone
You need to store the psftp script (lines from open
to bye
) into a separate file and pass that to psftp
using -b
switch:
cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"
Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b
EDIT: For username+password: As you cannot use psftp
commands in a batch file, for the same reason, you cannot specify the username and the password as psftp
commands. These are inputs to the open
command. While you can specify the username with the open
command (open <user>@<IP>
), you cannot specify the password this way. This can be done on a psftp
command line only. Then it's probably cleaner to do all on the command-line:
cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>
And remove the open
, <user>
and <PW>
lines from your script.txt
.
Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw
What you are doing atm is that you run psftp
without any parameter or commands. Once you exit it (like by typing bye
), your batch file continues trying to run open
command (and others), what Windows shell obviously does not understand.
If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:
(
echo cd ...
echo lcd ...
echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>
Suppose cellspcing
/ cellpadding
/ border-spacing
property did not worked, you can use the code as follow.
<div class="form-group">
<table width="100%" cellspacing="2px" style="border-spacing: 10px;">
<tr>
<td width="47%">
<input type="submit" class="form-control btn btn-info" id="submit" name="Submit" />
</td>
<td width="5%"></td>
<td width="47%">
<input type="reset" class="form-control btn btn-info" id="reset" name="Reset" />
</td>
</tr>
</table>
</div>
I've tried and got succeed while seperate the button by using table-width and make an empty td as 2 or 1% it doesn't return more different.
This came in handy for one of my requirements where I did not want to use CTE and also did not want to go with the inner join.
DECLARE @Ids varchar(50);
SET @Ids = '1,2,3,5,4,6,7,98,234';
SELECT
cn1,cn2,cn3
FROM tableName
WHERE columnName in (select Value from fn_SplitList(@ids, ','))
if (character == character.toLowerCase())
{
// The character is lowercase
}
else
{
// The character is uppercase
}
When you use scanner, as mentioned by Alnitak, you only get 'false' for hasNext() when you have a EOF character, basically... You cannot easily send and EOF character using the keyboard, therefore in situations like this, it's common to have a special character or word which you can send to stop execution, for example:
String s1 = sc.next();
if (s1.equals("exit")) {
break;
}
Break will get you out of the loop.
Consider an array of pointers. A pointer is really an address; so when you initialize the array, you are analogously telling the computer, "allocate this block of memory to hold these X numbers (which are addresses of other items)." Then if you change one of the pointers, you are just changing what it points to; it is still a numerical address which is itself sitting in the same spot.
A reference is analogous to an alias. If you were to declare an array of references, you would basically be telling the computer, "allocate this amorphous blob of memory consisting of all these different items scattered around."
No. You can't generically filter data without any context of what it's for. Sometimes you'd want to take a SQL query as input and sometimes you'd want to take HTML as input.
You need to filter input on a whitelist -- ensure that the data matches some specification of what you expect. Then you need to escape it before you use it, depending on the context in which you are using it.
The process of escaping data for SQL - to prevent SQL injection - is very different from the process of escaping data for (X)HTML, to prevent XSS.
Django code views.py
:
def view(request):
if request.method == 'POST':
print request.body
data = request.body
return HttpResponse(json.dumps(data))
HTML code view.html
:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#mySelect").change(function(){
selected = $("#mySelect option:selected").text()
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/view/',
data: {
'fruit': selected
},
success: function(result) {
document.write(result)
}
});
});
});
</script>
</head>
<body>
<form>
{{data}}
<br>
Select your favorite fruit:
<select id="mySelect">
<option value="apple" selected >Select fruit</option>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
</form>
</body>
</html>
Are you looking for something like this:
RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new MyDbContext()));
var str = RoleManager.Create(new IdentityRole(roleName));
Also check User Identity
git credential-manager clear Target Url: https://bitbucketxxxxxxxxxxxxxxxx.git
Delegates and Datasources of UICollectionView
//MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1 //return number of sections in collection view
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10 //return number of rows in section
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath)
configureCell(cell, forItemAtIndexPath: indexPath)
return cell //return your cell
}
func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
cell.backgroundColor = UIColor.blackColor()
//Customise your cell
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", forIndexPath: indexPath) as UICollectionReusableView
return view
}
//MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// When user selects the cell
}
override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
// When user deselects the cell
}
Building upon Anthony and Anton's answers I incorporated the ability to rotate the generated circle without affecting it's overall appearance. This is useful if you're using the path for an animation and you need to control where it begins.
function(cx, cy, r, deg){
var theta = deg*Math.PI/180,
dx = r*Math.cos(theta),
dy = -r*Math.sin(theta);
return "M "+cx+" "+cy+"m "+dx+","+dy+"a "+r+","+r+" 0 1,0 "+-2*dx+","+-2*dy+"a "+r+","+r+" 0 1,0 "+2*dx+","+2*dy;
}
For me I put my dependencies in the wrong spot.
buildscript {
dependencies {
//Don't put dependencies here.
}
}
dependencies {
//Put them here
}
The javaw.exe command is identical to java.exe, except that with javaw.exe there is no associated console window
Number 7 on the list is Jackson, not using Jerkson. It has support for Scala objects, (case classes etc).
Below is an example of how I use it.
object MyJacksonMapper extends JacksonMapper
val jsonString = MyJacksonMapper.serializeJson(myObject)
val myNewObject = MyJacksonMapper.deserializeJson[MyCaseClass](jsonString)
This makes it very simple. In addition is the XmlSerializer and support for JAXB Annotations is very handy.
This blog post describes it's use with JAXB Annotations and the Play Framework.
http://krasserm.blogspot.co.uk/2012/02/using-jaxb-for-xml-and-json-apis-in.html
Here is my current JacksonMapper.
trait JacksonMapper {
def jsonSerializer = {
val m = new ObjectMapper()
m.registerModule(DefaultScalaModule)
m
}
def xmlSerializer = {
val m = new XmlMapper()
m.registerModule(DefaultScalaModule)
m
}
def deserializeJson[T: Manifest](value: String): T = jsonSerializer.readValue(value, typeReference[T])
def serializeJson(value: Any) = jsonSerializer.writerWithDefaultPrettyPrinter().writeValueAsString(value)
def deserializeXml[T: Manifest](value: String): T = xmlSerializer.readValue(value, typeReference[T])
def serializeXml(value: Any) = xmlSerializer.writeValueAsString(value)
private[this] def typeReference[T: Manifest] = new TypeReference[T] {
override def getType = typeFromManifest(manifest[T])
}
private[this] def typeFromManifest(m: Manifest[_]): Type = {
if (m.typeArguments.isEmpty) { m.erasure }
else new ParameterizedType {
def getRawType = m.erasure
def getActualTypeArguments = m.typeArguments.map(typeFromManifest).toArray
def getOwnerType = null
}
}
}
You do this:
private void PassArray() {
String[] arrayw = new String[4]; //populate array
PrintA(arrayw);
}
private void PrintA(String[] a) {
//do whatever with array here
}
Just pass it as any other variable.
In Java, arrays are passed by reference.
Using sshpass works best. To just include your password in scp use the ' ':
scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/
I suggest you first call shutil.copytree
, and if an exception is thrown, then retry with shutil.copy
.
import shutil, errno
def copyanything(src, dst):
try:
shutil.copytree(src, dst)
except OSError as exc: # python >2.5
if exc.errno == errno.ENOTDIR:
shutil.copy(src, dst)
else: raise
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
This is the right way to compare strings:
int studentCompare = this.lastName.compareTo(s.getLastName());
This won't even compile:
if (this.getLastName() < s.getLastName())
Use
if (this.getLastName().compareTo(s.getLastName()) < 0)
instead.
So to compare fist/last name order you need:
int d = getFirstName().compareTo(s.getFirstName());
if (d == 0)
d = getLastName().compareTo(s.getLastName());
return d;
Although the gcc and g++ commands do very similar things, g++ is designed to be the command you'd invoke to compile a C++ program; it's intended to automatically do the right thing.
Behind the scenes, they're really the same program. As I understand, both decide whether to compile a program as C or as C++ based on the filename extension. Both are capable of linking against the C++ standard library, but only g++ does this by default. So if you have a program written in C++ that doesn't happen to need to link against the standard library, gcc will happen to do the right thing; but then, so would g++. So there's really no reason not to use g++ for general C++ development.
git push
is used to add commits you have done on the local repository to a remote one - together with git pull
, it allows people to collaborate.
Using split and regex :
var str = "fooBar0123".split(/(\d+)/);
console.log(str[0]); // fooBar
console.log(str[1]); // 0123
Hibernate tries to insert data that violate underlying database integrity contraints.
There's probably misconfiguration in hibernate persistent classes and/or mapping configuration (*.hbm.xml or annotations in persitent classes).
Maybe a property of the bean you want to save is not type-compatible with its related field in database (could explain the constraint [numbering]
part).
you may use great parseInt method
it will convert the leading digits to a number
parseInt("-10px");
// will give you -10
You can search for any scalar condition with:
>>> a = np.asarray([0,1,2,3,4])
>>> a == 0 # or whatver
array([ True, False, False, False, False], dtype=bool)
Which will give back the array as an boolean mask of the condition.
Thanks Patrick, you made my day! It's mousedown you have to use. However I've improved the code so you can handle a group of radio buttons.
//We need to bind click handler as well
//as FF sets button checked after mousedown, but before click
$('input:radio').bind('click mousedown', (function() {
//Capture radio button status within its handler scope,
//so we do not use any global vars and every radio button keeps its own status.
//This required to uncheck them later.
//We need to store status separately as browser updates checked status before click handler called,
//so radio button will always be checked.
var isChecked;
return function(event) {
//console.log(event.type + ": " + this.checked);
if(event.type == 'click') {
//console.log(isChecked);
if(isChecked) {
//Uncheck and update status
isChecked = this.checked = false;
} else {
//Update status
//Browser will check the button by itself
isChecked = true;
//Do something else if radio button selected
/*
if(this.value == 'somevalue') {
doSomething();
} else {
doSomethingElse();
}
*/
}
} else {
//Get the right status before browser sets it
//We need to use onmousedown event here, as it is the only cross-browser compatible event for radio buttons
isChecked = this.checked;
}
}})());
It's all about the selector. You can change your code to be something like this:
<div class="formbuilder">
<div class="active">Heading</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
Then use this javascript:
$(document).ready(function () {
$('.formbuilder div').on('click', function () {
$('.formbuilder div').removeClass('active');
$(this).addClass('active');
});
});
The example in a working jsfiddle
See this api about the selector I used: http://api.jquery.com/descendant-selector/
Just add margin: 0 auto;
to the inside div.
Your quotes are in the wrong spot. Here's a simple example:
<div style={{backgroundColor: "#FF0000"}}>red</div>
What the output that you need, select
or print
or .. so on.
so use the following code:
IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') select 1 else select 2
Try following these steps:
In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime()
gives you the mentioned milliseconds).
In your solution:
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();
long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);
you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.
Another possible solution would be to utilise the static fields of the Calendar
class:
//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);
Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.
It seems to work if you use
div#scrollable {
overflow-y: scroll;
height: 100%;
}
and add padding-bottom: 60px
to div.sidebar
.
For example: http://jsfiddle.net/AKL35/6/
However, I am unsure why it must be 60px
.
Also, you missed the f
from overflow-y: scroll;
Slightly different approach:
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("HeaderName", "value");
headers.add("Content-Type", "application/json");
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpEntity<ObjectToPass> request = new HttpEntity<ObjectToPass>(objectToPass, headers);
restTemplate.postForObject(url, request, ClassWhateverYourControllerReturns.class);
As others have mentioned you need a users/show.json view, but there are options to consider for the templating language...
ERB
Works out of the box. Great for HTML, but you'll quickly find it's awful for JSON.
Good solution. Have to add a dependency and learn its DSL.
Same deal as RABL: Good solution. Have to add a dependency and learn its DSL.
Plain Ruby
Ruby is awesome at generating JSON and there's nothing new to learn as you can call to_json
on a Hash or an AR object. Simply register the .rb extension for templates (in an initializer):
ActionView::Template.register_template_handler(:rb, :source.to_proc)
Then create the view users/show.json.rb:
@user.to_json
For more info on this approach see http://railscasts.com/episodes/379-template-handlers
(This was a comment to dilettante's answer but it got too long...hehe)
Of course a static is not needed here. You could use SharedPreferences to save, instead of static. Either way, the reason is to save the current progress so that its not too slow for complicated layouts. Because, in fact, after its used once, it will be rather fast later. However, I dont feel this is a good way to do it because if you have to rebuild your screen again (say onCreate
gets called again), then you probably want to start over from the beginning anyhow, eliminating the need for static. Therefore, just make it an instance variable instead of static.
Here is a smaller version that runs a bit faster and might be easier to read:
int fID = 0;
public int findUnusedId() {
while( findViewById(++fID) != null );
return fID;
}
This above function should be sufficient. Because, as far as I can tell, android-generated IDs are in the billions, so this will probably return 1
the first time and always be quite fast.
Because, it wont actually be looping past the used IDs to find an unused one. However, the loop is there should it actually find a used ID.
However, if you still want the progress saved between subsequent recreations of your app, and want to avoid using static. Here is the SharedPreferences version:
SharedPreferences sp = getSharedPreferences("your_pref_name", MODE_PRIVATE);
public int findUnusedId() {
int fID = sp.getInt("find_unused_id", 0);
while( findViewById(++fID) != null );
SharedPreferences.Editor spe = sp.edit();
spe.putInt("find_unused_id", fID);
spe.commit();
return fID;
}
This answer to a similar question should tell you everything you need to know about IDs with android: https://stackoverflow.com/a/13241629/693927
EDIT/FIX: Just realized I totally goofed up the save. I must have been drunk.
This is a sample method i created to validate email addresses, if the string parameter passed is a valid email address , it returns true, else false is returned.
private boolean validateEmailAddress(String emailAddress){
String expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = emailAddress;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
return matcher.matches();
}
You need to add url helper in config/autoload
$autoload['helper'] = array('form', 'url', 'file', 'html'); <-- Like This
Then you can use base_url or any kind of url.
If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a WeakMap
:
// Note that object must be an object or array,
// NOT a primitive value like string, number, etc.
var objIdMap=new WeakMap, objectCount = 0;
function objectId(object){
if (!objIdMap.has(object)) objIdMap.set(object,++objectCount);
return objIdMap.get(object);
}
var o1={}, o2={}, o3={a:1}, o4={a:1};
console.log( objectId(o1) ) // 1
console.log( objectId(o2) ) // 2
console.log( objectId(o1) ) // 1
console.log( objectId(o3) ) // 3
console.log( objectId(o4) ) // 4
console.log( objectId(o3) ) // 3
Using a WeakMap
instead of Map
ensures that the objects can still be garbage-collected.
class enum.Enum
is a class that solves all your enumeration needs, so you just need to inherit from it, and add your own fields. Then from then on, all you need to do is to just call it's attributes: name
& value
:
from enum import Enum
class Letter(Enum):
A = 1
B = 2
C = 3
print({i.name: i.value for i in Letter})
# prints {'A': 1, 'B': 2, 'C': 3}
Unless I'm badly mistaken libmagic
or -lmagic
is not the same library as ImageMagick. You state that you want ImageMagick.
ImageMagick comes with a utility to supply all appropriate options to the compiler.
Ex:
g++ program.cpp `Magick++-config --cppflags --cxxflags --ldflags --libs` -o "prog"
For MySql:
GROUP BY
DATE(`your_date_field`),
HOUR(`your_date_field`),
FLOOR( MINUTE(`your_date_field`) / 10);
I was getting an error
"ImportError: Install xlrd >= 1.0.0 for Excel support"
on Pycharm for below code
import pandas as pd
df2 = pd.read_excel("data.xlsx")
print(df2.head(3))
print(df2.tail(3))
Solution : pip install xlrd
It resolved error after using this.
Also no need to use "import xlrd
"
Is this what you are looking for:
myListBox.DataSource = MyList;
I did all things necessary to add bundling to an MVC 3 web (I'm new to the existing solution). Styles.Render
didn't work for me. I finally discovered I was simply missing a colon. In a master page: <%: Styles.Render("~/Content/Css") %>
I'm still confused about why (on the same page) <% Html.RenderPartial("LogOnUserControl"); %>
works without the colon.
A pointer to member function is different from a pointer to function. In order to use a member function through a pointer you need a pointer to it (obviously ) and an object to apply it to. So the appropriate version of function1
would be
void function1(void (aClass::*function)(int, int), aClass& a) {
(a.*function)(1, 1);
}
and to call it:
aClass a; // note: no parentheses; with parentheses it's a function declaration
function1(&aClass::test, a);
You can do it in CSS, but there isn't much support in browsers other than modern versions of Chrome, Safari and Opera at the moment. Firefox currently only supports SVG masks. See the Caniuse results for more information.
CSS:
p {
color: red;
-webkit-mask-image: -webkit-gradient(linear, left top, left bottom,
from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}
The trick is to specify a mask that is itself a gradient that ends as invisible (thru alpha value)
See a demo with a solid background, but you can change this to whatever you want.
Notice also that all the usual image properties are available for mask-image
p {_x000D_
color: red;_x000D_
font-size: 30px;_x000D_
-webkit-mask-image: linear-gradient(to left, rgba(0,0,0,1), rgba(0,0,0,0)), linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));_x000D_
-webkit-mask-size: 100% 50%;_x000D_
-webkit-mask-repeat: no-repeat;_x000D_
-webkit-mask-position: left top, left bottom;_x000D_
}_x000D_
_x000D_
div {_x000D_
background-color: lightblue;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
Now, another approach is available, that is supported by Chrome, Firefox, Safari and Opera.
The idea is to use
mix-blend-mode: hard-light;
that gives transparency if the color is gray. Then, a grey overlay on the element creates the transparency
div {_x000D_
background-color: lightblue;_x000D_
}_x000D_
_x000D_
p {_x000D_
color: red;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
width: 200px;_x000D_
mix-blend-mode: hard-light;_x000D_
}_x000D_
_x000D_
p::after {_x000D_
position: absolute;_x000D_
content: "";_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
background: linear-gradient(transparent, gray);_x000D_
pointer-events: none;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
To access files in my SD card, on my HTC One X (Android), I use this path:
file:///storage/sdcard0/folder/filename.jpg
Note the tripple "/" !
This command:
git ls-tree --full-tree -r --name-only HEAD
lists all of the already committed files being tracked by your git repo.
Reversing a ArrayList in a recursive way and without creating a new list for adding elements :
public class ListUtil {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
System.out.println("Reverse Order: " + reverse(arrayList));
}
public static <T> List<T> reverse(List<T> arrayList) {
return reverse(arrayList,0,arrayList.size()-1);
}
public static <T> List<T> reverse(List<T> arrayList,int startIndex,int lastIndex) {
if(startIndex<lastIndex) {
T t=arrayList.get(lastIndex);
arrayList.set(lastIndex,arrayList.get(startIndex));
arrayList.set(startIndex,t);
startIndex++;
lastIndex--;
reverse(arrayList,startIndex,lastIndex);
}
return arrayList;
}
}
add the onclick attribute
<div onclick="myFunction( event );"><span>shanghai</span><span>male</span></div>
To get the cursor to change use css's cursor rule.
div[onclick] {
cursor: pointer;
}
The selector uses an attribute selector which does not work in some versions of IE. If you want to support those versions, add a class to your div.
Here's a way to do it using PYTHONPATH
instead of the absolute path of your python libs dir:
for d in `echo "${PYTHONPATH}" | tr ':' '\n'`; do ls "${d}"; done
[ 10:43 Jonathan@MacBookPro-2 ~/xCode/Projects/Python for iOS/trunk/Python for iOS/Python for iOS ]$ for d in `echo "$PYTHONPATH" | tr ':' '\n'`; do ls "${d}"; done
libpython2.7.dylib pkgconfig python2.7
BaseHTTPServer.py _pyio.pyc cgitb.pyo doctest.pyo htmlentitydefs.pyc mimetools.pyc plat-mac runpy.py stringold.pyc traceback.pyo
BaseHTTPServer.pyc _pyio.pyo chunk.py dumbdbm.py htmlentitydefs.pyo mimetools.pyo platform.py runpy.pyc stringold.pyo tty.py
BaseHTTPServer.pyo _strptime.py chunk.pyc dumbdbm.pyc htmllib.py mimetypes.py platform.pyc runpy.pyo stringprep.py tty.pyc
Bastion.py _strptime.pyc chunk.pyo dumbdbm.pyo htmllib.pyc mimetypes.pyc platform.pyo sched.py stringprep.pyc tty.pyo
Bastion.pyc _strptime.pyo cmd.py
....
distinct
is not a function. It always operates on all columns of the select list.
Your problem is a typical "greatest N per group" problem which can easily be solved using a window function:
select ...
from (
select IDNo,
FirstName,
LastName,
....,
row_number() over (partition by lower(idno) order by firstname) as rn
from people
) t
where rn = 1;
Using the order by
clause you can select which of the duplicates you want to pick.
The above can be used in a left join, see below:
select ...
from x
left join (
select IDNo,
FirstName,
LastName,
....,
row_number() over (partition by lower(idno) order by firstname) as rn
from people
) p on p.idno = x.idno and p.rn = 1
where ...
This can be scripted in PL/SQL pretty simply based on the DBA/ALL/USER_CONSTRAINTS system view, but various details make not as trivial as it sounds. You have to be careful about the order in which it is done and you also have to take account of the presence of unique indexes.
The order is important because you cannot drop a unique or primary key that is referenced by a foreign key, and there could be foreign keys on tables in other schemas that reference primary keys in your own, so unless you have ALTER ANY TABLE privilege then you cannot drop those PKs and UKs. Also you cannot switch a unique index to being a non-unique index so you have to drop it in order to drop the constraint (for this reason it's almost always better to implement unique constraints as a "real" constraint that is supported by a non-unique index).
using this post
Open Firefox / chrome
open page the video
Play Video
click F12
on keyboard -> network
in Filter URLs
ts
copy link of ts
remove index and ts extension from link
for example:
http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000_454.ts
will be copied as
http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000
insert in below script under LINK
#!/bin/bash
# insert here urls
LINK=(
'http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000' # replace this with your url
)
mkdir my-videos
cd mkdir my-videos
CNT=0
for URL in ${LINK[@]}
do
# create folder for streaming media
CNT=$((CNT + 1))
mkdir $CNT
cd $CNT
(
DIR="${URL##*/}"
# download all videos
wget $URL'_'{0..1200}.ts
# link videos
echo $DIR'_'{0..1200}.ts | tr " " "\n" > tslist
while read line; do cat $line >> $CNT.mp4; done < tslist
rm -rf media* tslist
) &
cd ..
done
wait
EDIT
adding script in python - runs on windows and linux
import urllib.request
import os
import shutil
my_lessons = [
# http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000_454.ts
"http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000" # replace this with your url
]
lesson_dir = "my_vids"
try:
shutil.rmtree(lesson_dir)
except:
print "ok"
os.makedirs(lesson_dir)
os.chdir(lesson_dir)
for lesson, dwn_link in enumerate(my_lessons):
print ("downloading lesson %d.. " % (lesson), dwn_link)
file_name = '%04d.mp4' % lesson
f = open(file_name, 'ab')
for x in range(0, 1200):
try:
rsp = urllib.request.urlopen(dwn_link + "_%04d.ts" % (x) )
except:
break
file_name = '%d.mp4' % lesson
print "downloading %d.ts" % (x)
f.write(rsp.read())
f.close()
print "done good luck!! ================== "
if the script fails, or downloads empty file, try removing the try wrap to see what fails
You can use the Feed Dialog via URL to emulate the behavior of Sharer.php, but it's a little more complicated. You need a Facebook App setup with the Base URL of the URL you plan to share configured. Then you can do the following:
1) Create a link like:
http://www.facebook.com/dialog/feed?app_id=[FACEBOOK_APP_ID]' +
'&link=[FULLY_QUALIFIED_LINK_TO_SHARE_CONTENT]' +
'&picture=[LINK_TO_IMAGE]' +
'&name=' + encodeURIComponent('[CONTENT_TITLE]') +
'&caption=' + encodeURIComponent('[CONTENT_CAPTION]) +
'&description=' + encodeURIComponent('[CONTENT_DESCRIPTION]') +
'&redirect_uri=' + FBVars.baseURL + '[URL_TO_REDIRECT_TO_AFTER_SHARE]' +
'&display=popup';
(obviously replace the [CONTENT] with the appropriate content. Documentation here: https://developers.facebook.com/docs/reference/dialogs/feed)
2) Open that link in a popup window with JavaScript on click of the share link
3) I like to create file (i.e. popupclose.html) to redirect users back to when they finish sharing, this file will contain <script>window.close();</script>
to close the popup window
The only downside of using the Feed Dialog (besides setup) is that, if you manage Pages as well, you don't have the ability to choose to share via a Page, only a regular user account can share. And it can give you some really cryptic error messages, most of them are related to the setup of your Facebook app or problems with either the content or URL you are sharing.
I can confirm that this is not fixable by unregistering and registering the MSCOMCTRL.OCX like before. I have been trying to pin down which update is the source of the problem and it looks like it's either IE10 or IE10 in combination with some other update that's causing the problem. If I can get more time to invest in this I'll update my post but in the meantime uninstalling IE10 resolves the issue.
#include <stdio.h>
#include <time.h>
void main()
{
time_t t;
time(&t);
clrscr();
printf("Today's date and time : %s",ctime(&t));
getch();
}
I fixed my problem with the solution below:
implementation 'com.android.support:multidex:1.0.3'
multiDexEnabled true
In case you're using ASP.NET 5 with ASP.NET MVC 6, most of these answers simply won't work because you'll normally let MVC create the appropriate route collection for you (using the default RESTful conventions), meaning that you won't find any Routes.MapRoute()
call to edit at will.
The ConfigureServices()
method invoked by the Startup.cs
file will register MVC with the Dependency Injection framework built into ASP.NET 5: that way, when you call ApplicationBuilder.UseMvc()
later in that class, the MVC framework will automatically add these default routes to your app. We can take a look of what happens behind the hood by looking at the UseMvc()
method implementation within the framework source code:
public static IApplicationBuilder UseMvc(
[NotNull] this IApplicationBuilder app,
[NotNull] Action<IRouteBuilder> configureRoutes)
{
// Verify if AddMvc was done before calling UseMvc
// We use the MvcMarkerService to make sure if all the services were added.
MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);
var routes = new RouteBuilder
{
DefaultHandler = new MvcRouteHandler(),
ServiceProvider = app.ApplicationServices
};
configureRoutes(routes);
// Adding the attribute route comes after running the user-code because
// we want to respect any changes to the DefaultHandler.
routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
routes.DefaultHandler,
app.ApplicationServices));
return app.UseRouter(routes.Build());
}
The good thing about this is that the framework now handles all the hard work, iterating through all the Controller's Actions and setting up their default routes, thus saving you some redundant work.
The bad thing is, there's little or no documentation about how you could add your own routes. Luckily enough, you can easily do that by using either a Convention-Based and/or an Attribute-Based approach (aka Attribute Routing).
Convention-Based
In your Startup.cs class, replace this:
app.UseMvc();
with this:
app.UseMvc(routes =>
{
// Route Sample A
routes.MapRoute(
name: "RouteSampleA",
template: "MyOwnGet",
defaults: new { controller = "Items", action = "Get" }
);
// Route Sample B
routes.MapRoute(
name: "RouteSampleB",
template: "MyOwnPost",
defaults: new { controller = "Items", action = "Post" }
);
});
Attribute-Based
A great thing about MVC6 is that you can also define routes on a per-controller basis by decorating either the Controller
class and/or the Action
methods with the appropriate RouteAttribute
and/or HttpGet
/ HttpPost
template parameters, such as the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
namespace MyNamespace.Controllers
{
[Route("api/[controller]")]
public class ItemsController : Controller
{
// GET: api/items
[HttpGet()]
public IEnumerable<string> Get()
{
return GetLatestItems();
}
// GET: api/items/5
[HttpGet("{num}")]
public IEnumerable<string> Get(int num)
{
return GetLatestItems(5);
}
// GET: api/items/GetLatestItems
[HttpGet("GetLatestItems")]
public IEnumerable<string> GetLatestItems()
{
return GetLatestItems(5);
}
// GET api/items/GetLatestItems/5
[HttpGet("GetLatestItems/{num}")]
public IEnumerable<string> GetLatestItems(int num)
{
return new string[] { "test", "test2" };
}
// POST: /api/items/PostSomething
[HttpPost("PostSomething")]
public IActionResult Post([FromBody]string someData)
{
return Content("OK, got it!");
}
}
}
This controller will handle the following requests:
[GET] api/items
[GET] api/items/5
[GET] api/items/GetLatestItems
[GET] api/items/GetLatestItems/5
[POST] api/items/PostSomething
Also notice that if you use the two approaches togheter, Attribute-based routes (when defined) would override Convention-based ones, and both of them would override the default routes defined by UseMvc()
.
For more info, you can also read the following post on my blog.
I did the following to get my Mac to see the devices again:
android update adb
adb kill-server
adb start-server
At this point, calling adb devices
started returning devices again. Now run or debug your project to test it on your device.
if you can access the head add
<style>
/*...some style */
</style>
the way Hussein showed you
and the ultra hacky
<style>
</style>
in the html it will work but its ugly.
or javascript it the best way if you can use it in you case
You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:
-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
k NUMBER:= 0;
BEGIN
FOR i IN 1..10 LOOP
k:= k+1;
dbms_output.put_line(i||' '||k);
END LOOP;
END;
/
-- Cursor FOR loop --
set serveroutput on
DECLARE
CURSOR c1 IS SELECT * FROM scott.emp;
i NUMBER:= 0;
BEGIN
FOR e_rec IN c1 LOOP
i:= i+1;
dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
END LOOP;
END;
/
-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
FROM dual
CONNECT BY LEVEL <= 10
/
I ran across this issue today working with a clients program. The program works FINE in VS6.0 using the following: (I've changed it slightly)
//
// This is the one include file that every user-written Nextest programs needs.
// Patcom-generated files will also look for this file.
//
#include "stdio.h"
#define IS_NONE( a_key ) ( ( a_key == "none" || a_key == "N/A" ) ? TRUE : FALSE )
//
// Note in my environment we have output() which is printf which adds /n at the end
//
main {
char *psNameNone = "none";
char *psNameNA = "N/A";
char *psNameCAT = "CAT";
if (IS_NONE(psNameNone) ) {
output("psNameNone Matches NONE");
output("%s psNameNoneAddr 0x%x \"none\" addr 0x%X",
psNameNone,psNameNone,
"none");
} else {
output("psNameNone Does Not Match None");
output("%s psNameNoneAddr 0x%x \"none\" addr 0x%X",
psNameNone,psNameNone,
"none");
}
if (IS_NONE(psNameNA) ) {
output("psNameNA Matches N/A");
output("%s psNameNA 0x%x \"N/A\" addr 0x%X",
psNameNA,psNameNA,
"N/A");
} else {
output("psNameNone Does Not Match N/A");
output("%s psNameNA 0x%x \"N/A\" addr 0x%X",
psNameNA,psNameNA,
"N/A");
}
if (IS_NONE(psNameCAT)) {
output("psNameNA Matches CAT");
output("%s psNameNA 0x%x \"CAT\" addr 0x%X",
psNameNone,psNameNone,
"CAT");
} else {
output("psNameNA does not match CAT");
output("%s psNameNA 0x%x \"CAT\" addr 0x%X",
psNameNone,psNameNone,
"CAT");
}
}
If built in VS6.0 with Program Database with Edit and Continue. The compares APPEAR to work. With this setting STRING pooling is enabled, and the compiler optimizes all STRING pointers to POINT TO THE SAME ADDRESSS, so this can work. Any strings created on the fly after compile time will have DIFFERENT addresses so will fail the compare. Changing the setting to Program Database only will build the program so that it will fail.
I was able to fix this issue by changing $(document).ready()
to window.onLoad()
.
When you print it with this print 'I\nwould\nexpect\nmultiple\nlines'
you would get:
I
would
expect
multiple
lines
The \n
is a new line character specially used for marking END-OF-TEXT. It signifies the end of the line or text. This characteristics is shared by many languages like C, C++ etc.
Check sqlreader.IsDBNull(indexFirstName)
before you try to read it.
Python don't have a great support for recursion because of it's lack of TRE (Tail Recursion Elimination).
This means that each call to your recursive function will create a function call stack and because there is a limit of stack depth (by default is 1000) that you can check out by sys.getrecursionlimit
(of course you can change it using sys.setrecursionlimit but it's not recommended) your program will end up by crashing when it hits this limit.
As other answer has already give you a much nicer way for how to solve this in your case (which is to replace recursion by simple loop) there is another solution if you still want to use recursion which is to use one of the many recipes of implementing TRE in python like this one.
N.B: My answer is meant to give you more insight on why you get the error, and I'm not advising you to use the TRE as i already explained because in your case a loop will be much better and easy to read.
You can write JavaScript code in your file .
Put following code in your client side file:
<script>
window.onload = function(){
window.open(url, "_blank"); // will open new tab on window.onload
}
</script>
using jQuery.ready
<script>
$(document).ready(function(){
window.open(url, "_blank"); // will open new tab on document ready
});
</script>