Try this if you are using GET:
$curl = curl_init($url);
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache"
),
));
$response = curl_exec($curl);
curl_close($curl);
Well I'll begin with the second question: What are Web Services? , for obvious reasons.
WebServices are essentially pieces of logic(which you may vaguely refer to as a method) that expose certain functionality or data. The client implementing(technically speaking, consuming is the word) just needs to know what are the parameter(s) the method is going to accept and the type of data it is going to return(if at all it does).
The following Link says it all about REST & SOAP in an extremely lucid manner.
If you also want to know when to choose what (REST or SOAP), all the more reason to go through it!
public class testCrop extends AppCompatActivity {
ImageView iv;
String imagePath = "https://style.pk/wp-content/uploads/2015/07/omer-Shahzad-performed-umrah-600x548.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testcrpop);
iv = (ImageView) findViewById(R.id.testCrop);
imageDownload image = new imageDownload(testCrop.this, iv);
image.execute(imagePath);
}
class imageDownload extends AsyncTask<String, Integer, Bitmap> {
Context context;
ImageView imageView;
Bitmap bitmap;
InputStream in = null;
int responseCode = -1;
//constructor.
public imageDownload(Context context, ImageView imageView) {
this.context = context;
this.imageView = imageView;
}
@Override
protected void onPreExecute() {
}
@Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = httpURLConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap data) {
imageView.setImageBitmap(data);
saveImage(data);
}
private void saveImage(Bitmap data) {
File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test");
createFolder.mkdir();
File saveImage = new File(createFolder,"downloadimage.jpg");
try {
OutputStream outputStream = new FileOutputStream(saveImage);
data.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Make sure you added permission to write data in memory
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
In some C codestyle guide the typedef version is said to be preferred for "clarity" and "simplicity". I disagree, because the typedef obfuscates the real nature of the declared object. In fact, I don't use typedefs because when declaring a C variable I want to be clear about what the object actually is. This choice helps myself to remember faster what an old piece of code actually does, and will help others when maintaining the code in the future.
In my project I managed to use GridLayout and results are very stable, with no flickering and with a perfectly working vertical scrollbar.
First I created a JPanel for the settings; in my case it is a grid with a row for each parameter and two columns: left column is for labels and right column is for components. I believe your case is similar.
JPanel yourSettingsPanel = new JPanel();
yourSettingsPanel.setLayout(new GridLayout(numberOfParams, 2));
I then populate this panel by iterating on my parameters and alternating between adding a JLabel and adding a component.
for (int i = 0; i < numberOfParams; ++i) {
yourSettingsPanel.add(labels[i]);
yourSettingsPanel.add(components[i]);
}
To prevent yourSettingsPanel from extending to the entire container I first wrap it in the north region of a dummy panel, that I called northOnlyPanel.
JPanel northOnlyPanel = new JPanel();
northOnlyPanel.setLayout(new BorderLayout());
northOnlyPanel.add(yourSettingsPanel, BorderLayout.NORTH);
Finally I wrap the northOnlyPanel in a JScrollPane, which should behave nicely pretty much anywhere.
JScrollPane scroll = new JScrollPane(northOnlyPanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Most likely you want to display this JScrollPane extended inside a JFrame; you can add it to a BorderLayout JFrame, in the CENTER region:
window.add(scroll, BorderLayout.CENTER);
In my case I put it on the left column of a GridLayout(1, 2) panel, and I use the right column to display contextual help for each parameter.
JTextArea help = new JTextArea();
help.setLineWrap(true);
help.setWrapStyleWord(true);
help.setEditable(false);
JPanel split = new JPanel();
split.setLayout(new GridLayout(1, 2));
split.add(scroll);
split.add(help);
XHR polling A Request is answered when the event occurs (could be straight away, or after a delay). Subsequent requests will need to made to receive further events.
The browser makes an asynchronous request of the server, which may wait for data to be available before responding. The response can contain encoded data (typically XML or JSON) or Javascript to be executed by the client. At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs. Wikipedia
Server Sent Events Client sends request to server. Server sends new data to webpage at any time.
Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. Mozilla
WebSockets After the initial handshake (via HTTP protocol). Communication is done bidirectionally using the WebSocket protocol.
The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. Once the connection is established, communication switches to a bidirectional binary protocol which does not conform to the HTTP protocol. Wikipedia
echo "blahblah"> txt.txt
will erase the txt and put blahblah in it's place
echo "blahblah">> txt.txt
will write blahblah on a new line in the txt
I think that both will create a new txt if none exists (I know that the first one does)
Where "txt.txt
" is written above, a file path can be inserted if wanted. e.g. C:\Users\<username>\desktop
, which will put it on their desktop.
On my Ubuntu VM, with 1048 MB total RAM, java -XX:+PrintFlagsFinal -version | grep HeapSize
printed : uintx MaxHeapSize := 266338304
, which is approx 266MB and is 1/4th of my total RAM.
If you want to try with java code. Here you go -
final LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
yourView.setLayoutParams(params);
params.gravity = Gravity.BOTTOM; // set gravity
I came upon a similar issue recently and following Fabian's advice actually led me to the solution. Turns out with client certs you have to ensure two things:
The private key is actually being exported as part of the cert.
The application pool identity running the app has access to said private key.
In our case I had to:
The trusted root issue explained in other answers is a valid one, it was just not the issue in our case.
Could you use the SQLPATH environment variable to tell sqlplus where to look for the scripts you are trying to run? I believe you could use HOST to set SQLPATH in the script too.
There could potentially be problems if two scripts have the same name and both directories are in the SQLPATH.
It's a bit surprising seeing multiple answers suggesting to use python
for this task, as there's no need to write a multi-line program for this.
Standard Unix tools like sed
, awk
or perl
can achieve this easily straight from the command-line.
e.g anywhere you have perl
(Windows, Mac, Linux) the following should achieve what the OP asked:
perl -i -pe 's/[ \t]+$//;' files...
Explanation of the arguments to perl
:
-i # run the edit "in place" (modify the original file)
-p # implies a loop with a final print over every input line
-e # next arg is the perl expression to apply (to every line)
s/[ \t]$//
is a substitution regex s/FROM/TO/: replace every trailing (end of line) non-empty space (spaces or tabs) with nothing.
Advantages:
Edit:
Newer versions of
perl
support\h
(any horizontal-space character), so the solution becomes even shorter:
perl -i -pe 's/\h+$//;' files...
More generally, if you want to modify any number of files directly from the command line, replacing every appearance of FOO
with BAR
, you may always use this generic template:
perl -i -pe 's/FOO/BAR/' files...
I would use
WHERE columnName LIKE '%[%]%'
SQL Server stores string summary statistics for use in estimating the number of rows that will match a LIKE
clause. The cardinality estimates can be better and lead to a more appropriate plan when the square bracket syntax is used.
The response to this Connect Item states
We do not have support for precise cardinality estimation in the presence of user defined escape characters. So we probably get a poor estimate and a poor plan. We'll consider addressing this issue in a future release.
An example
CREATE TABLE T
(
X VARCHAR(50),
Y CHAR(2000) NULL
)
CREATE NONCLUSTERED INDEX IX ON T(X)
INSERT INTO T (X)
SELECT TOP (5) '10% off'
FROM master..spt_values
UNION ALL
SELECT TOP (100000) 'blah'
FROM master..spt_values v1, master..spt_values v2
SET STATISTICS IO ON;
SELECT *
FROM T
WHERE X LIKE '%[%]%'
SELECT *
FROM T
WHERE X LIKE '%\%%' ESCAPE '\'
Shows 457 logical reads for the first query and 33,335 for the second.
X <- c(1:3)*0
Maybe this is not the most efficient way to initialize a vector to zero, but this requires to remember only the c()
function, which is very frequently cited in tutorials as a usual way to declare a vector.
As as side-note: To someone learning her way into R from other languages, the multitude of functions to do same thing in R may be mindblowing, just as demonstrated by the previous answers here.
If your data is already in array form, it's really simple using jQuery:
$(data.msg).each(function()
{
alert(this.value);
alert(this.label);
//this refers to the current item being iterated over
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('#myDropDown').append(option);
});
.ajax()
is more flexible than .getJSON()
- for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().
q = request.GET.get("q", None)
if q:
message = 'q= %s' % q
else:
message = 'Empty'
What you want is maxlength
.
Valid for
text
,search
,url
,tel
,password
, it defines the maximum number of characters (as UTF-16 code units) the user can enter into the field. This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the field has no maximum length. This value must also be greater than or equal to the value of minlength.
You might consider using one of these input
types.
int add(int x, int y); // forward declaration using function prototype
Can you explain "forward declaration" more further? What is the problem if we use it in the main() function?
It's same as #include"add.h"
. If you know,preprocessor expands the file which you mention in #include
, in the .cpp file where you write the #include
directive. That means, if you write #include"add.h"
, you get the same thing, it is as if you doing "forward declaration".
I'm assuming that add.h
has this line:
int add(int x, int y);
Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.
OR
y + ̆ = y̆ which actually is
y + ̆ = y̆
Since you can stack them one atop the other you can produce the following:
y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
which actually is:
y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
The same goes for putting stuff underneath:
y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
that in fact is:
y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.
To produce a list of combining diacritical marks you can use the following script (since links keep on dying)
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +" "+"&#"+i+";");}
_x000D_
Also check em out
Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾
As of the comment: You should be able to use Apache Commons ReverseListIterator
Iterable<String> reverse
= new IteratorIterable(new ReverseListIterator(stringList));
for(String string: reverse ){
//...do something
}
As @rogerdpack said, you need to wrap the ReverseListIterator
as an Iterable
.
var regex = /\d+/g;_x000D_
var string = "you can enter maximum 500 choices";_x000D_
var matches = string.match(regex); // creates array from matches_x000D_
_x000D_
document.write(matches);
_x000D_
References:
http://www.regular-expressions.info/javascript.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
You can do it in this way
// xyz.h
#ifndef _XYZ_
#define _XYZ_
template <typename XYZTYPE>
class XYZ {
//Class members declaration
};
#include "xyz.cpp"
#endif
//xyz.cpp
#ifdef _XYZ_
//Class definition goes here
#endif
This has been discussed in Daniweb
Also in FAQ but using C++ export keyword.
If the machine is being a firewall then your solution is a very sensible one: the alternative being able to query the firewall which ends-up being very dependent on the type of firewall (if at all possible).
You have to use double double quotes to escape the double quotes (lol):
g = "abcd """ & a & """"
To compatibility with both py2 and py3
import six
import base64
def b64encode(source):
if six.PY3:
source = source.encode('utf-8')
content = base64.b64encode(source).decode('utf-8')
A more structured way to get this is to use UriBuilder. This avoids direct string manipulation.
var builder = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port);
Below given some information about fav Icon
What Is FavIcon? ? FavIcon is nothing but small image which appears top left along with the application address bar title.Standard size specification for favicon.ico is 16 by 16 pixel. Please see below attached figure.
How It Works ? ? Usually we add our FavIcon.ico image in the route solution folder and automatically application picks it while running. But most of the time we might have to use below both link reference.
<link rel="icon" href="favicon.ico" type="image/ico"/>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
Some browser expect one (rel="icon") Some other browser expect other rel="shortcut icon"
? Type=”image/x-icon” OR Type=”image/ico”: once expect exact ico image and one expect any image even formatted from .jpg or .pn ..etc.
? We have to use above two tags to the common pages like – Master page , Main frame which is getting used in all the pages
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
You can try like following:
string output = JsonConvert.SerializeObject(jsonStr);
The answer varies depending on what storage engine you're using. The ideal scenario is if you're using InnoDB. In that case you can use the --single-transaction
flag, which will give you a coherent snapshot of the database at the time that the dump begins.
After installing Free BitDefender AntiVirus the services related to the AntiVirus used about 80 MB of my computer's Memory. I also noticed that after installing BitDefender the service related to windows Presentation Font Cache was also installed: "WPFFontCache_v0300.exe". I disabled the service from stating automatically and now BitDefender Free AntiVirus use only 15-20 MB (!!!) of my computer's Memory! As far as I concern, this service affected negatively the memory usage of my PC inother services. I recommend you to disable it.
The ngRoute module is no longer part of the core angular.js
file. If you are continuing to use $routeProvider then you will now need to include angular-route.js
in your HTML:
<script src="angular.js">
<script src="angular-route.js">
You also have to add ngRoute
as a dependency for your application:
var app = angular.module('MyApp', ['ngRoute', ...]);
If instead you are planning on using angular-ui-router
or the like then just remove the $routeProvider
dependency from your module .config()
and substitute it with the relevant provider of choice (e.g. $stateProvider
). You would then use the ui.router
dependency:
var app = angular.module('MyApp', ['ui.router', ...]);
I will break answer on three paragraphs.
Part 1:
git stash
(To save your un-committed changes in a "stash". Note: this removes changes from working tree!)
git checkout some_branch
(change to intended branch -- in this case some_branch
)
git stash list
(list stashes)
You can see:
stash@{0}: WIP on {branch_name}: {SHA-1 of last commit} {last commit of you branch}
stash@{0}: WIP on master: 085b095c6 modification for test
git stash apply
(to apply stash to working tree in current branch)
git stash apply stash@{12}
(if you will have many stashes you can choose what stash will apply -- in this case we apply stash 12
)
git stash drop stash@{0}
(to remove from stash list -- in this case stash 0
)
git stash pop stash@{1}
(to apply selected stash and drop it from stash list)
Part 2:
You can hide your changes with this command but it is not necessary.
You can continue on the next day without stash.
This commands for hide your changes and work on different branches or for implementation some realisation of your code and save in stashes without branches and commitsor your custom case!
And later you can use some of stashes and check wich is better.
Part 3:
Stash command for local hide your changes.
If you want work remotely you must commit and push.
The following command will create a copy in a new window. So you can continue see both original file and the new file.
:w {newfilename} | sp #
This is almost certainly much slower than any other version given here, but it was fun to write.
static bool ByteArrayEquals(byte[] a1, byte[] a2)
{
return a1.Zip(a2, (l, r) => l == r).All(x => x);
}
In my case I had no SDK selected for my project(not sure why). Simply went to Project Structure dialog (alt+ctrl+shift+s
or button 1 on the screen) and then to project-> Project SDK's was selected <no SDK>
. Just changed it to the latest
Here is a solution:
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Integer[] iArray = Arrays.stream(array).boxed().toArray(Integer[]::new);
System.out.println(Arrays.toString(iArray));
List<Integer> list = new ArrayList<>();
Collections.addAll(list, iArray);
System.out.println(list);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Another possibility would be grouping, similar to how you might approach it in raw SQL:
from y in context.MyTable
group y.MyCounter by y.MyField into GrpByMyField
where GrpByMyField.Key == value
select GrpByMyField.Max()
The only thing is (testing again in LINQPad) switching to the VB LINQ flavor gives syntax errors on the grouping clause. I'm sure the conceptual equivalent is easy enough to find, I just don't know how to reflect it in VB.
The generated SQL would be something along the lines of:
SELECT [t1].[MaxValue]
FROM (
SELECT MAX([t0].[MyCounter) AS [MaxValue], [t0].[MyField]
FROM [MyTable] AS [t0]
GROUP BY [t0].[MyField]
) AS [t1]
WHERE [t1].[MyField] = @p0
The nested SELECT looks icky, like the query execution would retrieve all rows then select the matching one from the retrieved set... the question is whether or not SQL Server optimizes the query into something comparable to applying the where clause to the inner SELECT. I'm looking into that now...
I'm not well-versed in interpreting execution plans in SQL Server, but it looks like when the WHERE clause is on the outer SELECT, the number of actual rows resulting in that step is all rows in the table, versus only the matching rows when the WHERE clause is on the inner SELECT. That said, it looks like only 1% cost is shifted to the following step when all rows are considered, and either way only one row ever comes back from the SQL Server so maybe it's not that big of a difference in the grand scheme of things.
This is a fairly standard communication question. One approach would be to use a ResultReceiver in Activity A:
Intent GotoB=new Intent(A.this,B.class);
GotoB.putExtra("finisher", new ResultReceiver(null) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
A.this.finish();
}
});
startActivityForResult(GotoB,1);
and then in Activity B you can just finish it on demand like so:
((ResultReceiver)getIntent().getExtra("finisher")).send(1, new Bundle());
Try something like that.
If you compile with optimizations enabled, then many variables will be removed; for example:
SomeType value = GetValue();
DoSomething(value);
here the local variable value
would typically get removed, keeping the value on the stack instead - a bit like as if you had written:
DoSomething(GetValue());
Also, if a return value isn't used at all, then it will be dropped via "pop" (rather than stored in a local via "stloc", and again; the local will not exist).
Because of this, in such a build the debugger can't get the current value of value
because it doesn't exist - it only exists for the brief instant between GetValue()
and DoSomething(...)
.
So; if you want to debug... don't use a release build! or at least, disable optimizations while you debug.
AND is &&
and OR is ||
like in C.
Actually, there is a way to rename a folder using web interface.
See https://github.com/blog/1436-moving-and-renaming-files-on-github
Based on what you all shared I was able to put this together:
#!/usr/bin/env bash
VAR1="192.168.1.20 192.168.1.126 192.168.1.36"
for a in $VAR1; do { ssh -t -t $a -l Administrator "sudo softwareupdate -l"; } & done;
WAITPIDS="$WAITPIDS "$!;...; wait $WAITPIDS
echo "Script has finished"
Exit 1
This lists all the updates on the mac on three machines at once. Later on I used it to perform a software update for all machines when i CAT my ipaddress.txt
It looks like you are trying to parse each line. You've been shown by another answer how to use getline
in a loop to seperate each line. The other tool you are going to want is istringstream
, to seperate each token.
std::string line;
while(std::getline(file, line))
{
std::istringstream iss(line);
std::string token;
while (iss >> token)
{
// do something with token
}
}
"True" and "False" do not work, to disable, set to value disabled.
$('.someElement').attr('disabled', 'disabled');
To enable, remove.
$('.someElement').removeAttr('disabled');
Also, don't worry about multiple items being selected, jQuery will operate on all of them that match. If you need just one you can use many things :first, :last, nth, etc.
You are using name and not id as other mention -- remember, if you use id valid xhtml requires the ids be unique.
You can also try Word Extractor tool. Word Extractor can be used with any file in your computer to separate the strings that contain human text / words from binary code (exe applications, DLLs).
You can use the 'describe pod' syntax
For OpenShift use:
oc describe pod <pod-id>
For vanilla Kubernetes:
kubectl describe pod <pod-id>
Examine the events of the output. In my case it shows Back-off pulling image coredns/coredns:latest
In this case the image coredns/coredns:latest can not be pulled from the Internet.
Events:
FirstSeen LastSeen Count From SubObjectPath Type Reason Message
--------- -------- ----- ---- ------------- -------- ------ -------
5m 5m 1 {default-scheduler } Normal Scheduled Successfully assigned coredns-4224169331-9nhxj to 192.168.122.190
5m 1m 4 {kubelet 192.168.122.190} spec.containers{coredns} Normal Pulling pulling image "coredns/coredns:latest"
4m 26s 4 {kubelet 192.168.122.190} spec.containers{coredns} Warning Failed Failed to pull image "coredns/coredns:latest": Network timed out while trying to connect to https://index.docker.io/v1/repositories/coredns/coredns/images. You may want to check your internet connection or if you are behind a proxy.
4m 26s 4 {kubelet 192.168.122.190} Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "coredns" with ErrImagePull: "Network timed out while trying to connect to https://index.docker.io/v1/repositories/coredns/coredns/images. You may want to check your Internet connection or if you are behind a proxy."
4m 2s 7 {kubelet 192.168.122.190} spec.containers{coredns} Normal BackOff Back-off pulling image "coredns/coredns:latest"
4m 2s 7 {kubelet 192.168.122.190} Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "coredns" with ImagePullBackOff: "Back-off pulling image \"coredns/coredns:latest\""
Additional debuging steps
Look here http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#deriveFont%28float%29
JComponent has a setFont() method. You will control the font there, not on the String.
Such as
JButton b = new JButton();
b.setFont(b.getFont().deriveFont(18.0f));
Solution posted by Denys S. in the question post:
I quite messed it up with c to c++ conversion (basically env
variable stuff), but I got it working with the following code for C++:
#include <string.h>
#include <stdio.h>
#include <jni.h>
jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){
jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);
const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
printf("%s\n", str);
return (*env)->NewStringUTF(env, str);
}
And next code for java methods:
public class MainActivity extends Activity {
private static String LIB_NAME = "thelib";
static {
System.loadLibrary(LIB_NAME);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textview);
tv.setText(this.getJniString());
}
// please, let me live even though I used this dark programming technique
public String messageMe(String text) {
System.out.println(text);
return text;
}
public native String getJniString();
}
What have you tried? This should work.
h1 { font-size: 20pt; }
h2 { font-size: 16pt; }
You need to change it at "class": "sidebar_label"
Example, in your .sublime-theme file:
// Sidebar entry
{
"class": "sidebar_label",
"color": [212, 212, 213],
"shadow_offset": [0, 0],
"font.size":13
}
When speaking with remote machines, Ansible by default assumes you are using SSH keys. SSH keys are encouraged but password authentication can also be used where needed by supplying the option --ask-pass. If using sudo features and when sudo requires a password, also supply --ask-become-pass (previously --ask-sudo-pass which has been deprecated).
Never used the feature but the docs say you can.
for horizontal line on the layout :
<View
android:id="@+id/View03"
android:layout_width="fill_parent"
android:layout_height="5dip"
android:background="#0f0" />
for vertical line on the layout :
<View
android:id="@+id/View04"
android:layout_width="5dip"
android:layout_height="fill_parent"
android:background="#0f0" />
Chain selectors are not limited just to classes, you can do it for both classes and ids.
Classes
.classA.classB {
/*style here*/
}
Class & Id
.classA#idB {
/*style here*/
}
Id & Id
#idA#idB {
/*style here*/
}
All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".
For your case
li.left.ui-class-selector {
/*style here*/
}
or
.left.ui-class-selector {
/*style here*/
}
With SQLServer 2005 Express, what I found was that even with autocommit off, insertions into a Db table were committed without my actually issuing a commit command from the Management Studio session. The only difference was, when autocommit was off, I could roll back all the insertions; with *autocommit on, I could not.* Actually, I was wrong. With autocommit mode off, I see the changes only in the QA (Query Analyzer) window from which the commands were issued. If I popped a new QA (Query Analyzer) window, I do not see the changes made by the first window (session), i.e. they are NOT committed! I had to issue explicit commit or rollback commands to make changes visible to other sessions(QA windows) -- my bad! Things are working correctly.
In my case (Spring MVC + Hibernate project), I added Controller, Service, Dao, Model class & Thyme leaf page. Just didn't map new model class in "hibernate.cfg.xml" file. So that got this error. But after mapping new model class again got the error. Then deleted Controller, Service, Dao, Model class. Thyme leaf page and Created newly. Also mapped new model class. Then error has gone.
Are you sure your processor supports Intel Virtualization (VT-x) or AMD Virtualization (AMD-V)?
Here you can find Hardware-Assisted Virtualization Detection Tool ( http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0ee2a17f-8538-4619-8d1c-05d27e11adb2&displaylang=en) which will tell you if your hardware supports VT-x.
Alternatively you can find your processor here: http://ark.intel.com/Default.aspx. All AMD processors since 2006 supports Virtualization.
md5sum
puts backslash before hash if there is backslash in file name. First 32 characters or anything before first space may not be a proper hash. It will not happen when using standard input (file name will be just -), so pixelbeat's answer will work, but many others will require adding something like | tail -c 32
.
A simple keymap in vim would solve this issue. map viq F”lvf”hh This above command maps viq to the keys to search between quotes. Replace " with any character and create your keymaps. Stick this in vimrc during startup and you should be able to use it everytime.
This indicates you are trying to put something too big into a column. For example, you have a VARCHAR2(10) column and you are putting in 11 characters. Same thing with number.
This is happening at line 176 of package UMAIN. You would need to go and have a look at that to see what it is up to. Hopefully you can look it up in your source control (or from user_source). Later versions of Oracle report this error better, telling you which column and what value.
Actually if you do Ctrl+W W
, you won't need to add that extra Ctrl
. Does the same thing.
Let's discuss the three ways of handling business logic in AngularJS in a simple way: (Inspired by Yaakov's Coursera AngularJS course)
SERVICE:
Syntax:
app.js
var app = angular.module('ServiceExample',[]);
var serviceExampleController =
app.controller('ServiceExampleController', ServiceExampleController);
var serviceExample = app.service('NameOfTheService', NameOfTheService);
ServiceExampleController.$inject = ['NameOfTheService'] //protects from minification of js files
function ServiceExampleController(NameOfTheService){
serviceExampleController = this;
serviceExampleController.data = NameOfTheService.getSomeData();
}
function NameOfTheService(){
nameOfTheService = this;
nameOfTheService.data = "Some Data";
nameOfTheService.getSomeData = function(){
return nameOfTheService.data;
}
}
index.html
<div ng-controller = "ServiceExampleController as serviceExample">
{{serviceExample.data}}
</div>
Features of Service:
FACTORY
First let's have a look at the syntax:
app.js:
var app = angular.module('FactoryExample',[]);
var factoryController = app.controller('FactoryController', FactoryController);
var factoryExampleOne = app.factory('NameOfTheFactoryOne', NameOfTheFactoryOne);
var factoryExampleTwo = app.factory('NameOfTheFactoryTwo', NameOfTheFactoryTwo);
//first implementation where it returns a function
function NameOfTheFactoryOne(){
var factory = function(){
return new SomeService();
}
return factory;
}
//second implementation where an object literal would be returned
function NameOfTheFactoryTwo(){
var factory = {
getSomeService : function(){
return new SomeService();
}
};
return factory;
}
Now using the above two in the controller:
var factoryOne = NameOfTheFactoryOne() //since it returns a function
factoryOne.someMethod();
var factoryTwo = NameOfTheFactoryTwo.getSomeService(); //accessing the object
factoryTwo.someMethod();
Features of Factory:
.service()
method is a factory that always produces the same type of service, which is a singleton, and without any easy way to configure it's behavior. That .service()
method is usually used as a shortcut for something that doesn't require any configuration whatsoever. PROVIDER
Let's again have a look at the Syntax first:
angular.module('ProviderModule', [])
.controller('ProviderModuleController', ProviderModuleController)
.provider('ServiceProvider', ServiceProvider)
.config(Config); //optional
Config.$inject = ['ServiceProvider'];
function Config(ServiceProvider) {
ServiceProvider.defaults.maxItems = 10; //some default value
}
ProviderModuleController.$inject = ['ServiceProvider'];
function ProviderModuleController(ServiceProvider) {
//some methods
}
function ServiceProvider() {
var provider = this;
provider.defaults = {
maxItems: 10
};
provider.$get = function () {
var someList = new someListService(provider.defaults.maxItems);
return someList;
};
}
}
Features of Provider:
.service
or .factory
methods. $get
is a function that is directly attached to the provider instance. That function is a factory function. In other words, it's just like the one that we use to provide to the .factory
method. In that function, we create our own service. This $get
property, that's a function, is what makes the provider a provider. AngularJS expects the provider to have a $get property whose value is a function that Angular will treat as a factory function. But what makes this whole provider setup very special, is the fact that we can provide some config
object inside the service provider, and that usually comes with defaults that we can later overwrite in the step, where we can configure the entire application.Um, lots.
There are several parameters here. The specific VM, plus there are usually run-time parameters on the VM as well. That's somewhat driven by the operating system: what support does the underlying OS have for threads and what limitations does it put on them? If the VM actually uses OS-level threads at all, the good old red thread/green thread thing.
What "support" means is another question. If you write a Java program that is just something like
class DieLikeADog {
public static void main(String[] argv){
for(;;){
new Thread(new SomeRunaable).start();
}
}
}
(and don't complain about little syntax details, I'm on my first cup of coffee) then you should certainly expect to get hundreds or thousands of threads running. But creating a Thread is relatively expensive, and scheduler overhead can get intense; it's unclear that you could have those threads do anything useful.
Okay, couldn't resist. Here's my little test program, with a couple embellishments:
public class DieLikeADog {
private static Object s = new Object();
private static int count = 0;
public static void main(String[] argv){
for(;;){
new Thread(new Runnable(){
public void run(){
synchronized(s){
count += 1;
System.err.println("New thread #"+count);
}
for(;;){
try {
Thread.sleep(1000);
} catch (Exception e){
System.err.println(e);
}
}
}
}).start();
}
}
}
On OS/X 10.5.6 on Intel, and Java 6 5 (see comments), here's what I got
New thread #2547 New thread #2548 New thread #2549 Can't create thread: 5 New thread #2550 Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread at java.lang.Thread.start0(Native Method) at java.lang.Thread.start(Thread.java:592) at DieLikeADog.main(DieLikeADog.java:6)
Initial Check.
1) When you are exporting the DISPLAY to other machine, ensure you entered the command xhost +
on that machine. This command allows to other machine to export their DISPLAY on this machine. There may be security constraints, just know about it. Need to check ssh -X MachineIP
will not require xhost +
?
2) Some times JCONSOLE
won't show all its process, since those JVM process may run with different user and you are exporting the DISPLAY with another user. so better follow CD_DIR>sudo ./jconsole
3) In WAS (WEBSPHERE); jconsole won't be able to connect its java server process, that time just go till the link, then try connecting it. This worked for me. May be this page is initializing some variables to enable jconsole to connect with that server.
WAS console > Application servers > server1 > Process definition > Java Virtual Machine
I have faced the same issue with AIX (where command line interface only available, There is no DISPLAY UI) machine. I resolved by installing
NX Client for Windows
Step 1: Through that Windows machine, I connected with unix box where GUI console is available.
Step 2: SSH to the AIX box from that UNIX box.
Step 3: set DISPLAY like "export DISPLAY=UNIXMACHINE:NXClientPORTConnectedMentionedOnTitle"
Step 4: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.
VNC
If you installed VNC on UNIX box where display is available; then Windows and NX Client is not required.
Step 1: Use VNC to connect with Unix box where GUI console is available.
Step 2: SSH to the AIX box from that UNIX box.
Step 3: set DISPLAY like "export DISPLAY=UNIXMACHINE:VNCPORT"
Step 4: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.
ELSE
Step 1: SSH to the AIX box from that UNIX box.
Step 2: set DISPLAY like "export DISPLAY=UNIXMACHINE:VNCPORT"
Step 3: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.
If you have private certs to deal with, like your orgs own CA root and intermediates part of the chain, then better to add the certs to the ca file viz. cacert.pem than bypassing the entire security apparatus (verify=False). Below code gets you going in both 2.7+ and 3+
Consider adding the whole cert chain and off course you need to do this only once.
import certifi
cafile=certifi.where() # cacert file
with open ('rootca.pem','rb') as infile:
customca=infile.read()
with open(cafile,'ab') as outfile:
outfile.write(customca)
with open ('interca.pem','rb') as infile:
customca=infile.read()
with open(cafile,'ab') as outfile:
outfile.write(customca)
with open ('issueca.pem','rb') as infile:
customca=infile.read()
with open(cafile,'ab') as outfile:
outfile.write(customca)
Then this should get you going
import requests
response = requests.request("GET", 'https://yoursecuresite.com', data = {})
print(response.text.encode('utf8'))
Hope this helps
In additional you should disable your antivirus or manage it to open 80 port on your system.
Probably you can implement generic static lookup
method.
Like so
public class LookupUtil {
public static <E extends Enum<E>> E lookup(Class<E> e, String id) {
try {
E result = Enum.valueOf(e, id);
} catch (IllegalArgumentException e) {
// log error or something here
throw new RuntimeException(
"Invalid value for enum " + e.getSimpleName() + ": " + id);
}
return result;
}
}
Then you can
public enum MyEnum {
static public MyEnum lookup(String id) {
return LookupUtil.lookup(MyEnum.class, id);
}
}
or call explicitly utility class lookup method.
A difference is that "foo".equals((String)null)
returns false while "foo".compareTo((String)null) == 0
throws a NullPointerException. So they are not always interchangeable even for Strings.
aca definis los anchos
float[] anchoDeColumnas= new float[] {10f, 20f, 30f, 10f};
aca se los insertas a la tabla que tiene las columnas
table.setWidths(anchoDeColumnas);
How about this one? The idea was to use only one loop. And, who knows, maybe you're using only IList implementations thorough your code and you don't want to cast to List.
private IEnumerable<IList<T>> SplitList<T>(IList<T> list, int totalChunks)
{
IList<T> auxList = new List<T>();
int totalItems = list.Count();
if (totalChunks <= 0)
{
yield return auxList;
}
else
{
for (int i = 0; i < totalItems; i++)
{
auxList.Add(list[i]);
if ((i + 1) % totalChunks == 0)
{
yield return auxList;
auxList = new List<T>();
}
else if (i == totalItems - 1)
{
yield return auxList;
}
}
}
}
I suppose that 255 in 227./255 is perceived as an integer and divide is always return 0
using System;
using System.Data;
using System.Data.SqlClient;
namespace SqlCommend
{
class sqlcreateapp
{
static void Main(string[] args)
{
try
{
SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
SqlCommand cmd = new SqlCommand("create table <Table Name>(empno int,empname varchar(50),salary money);", conn);
conn.Open();
cmd.ExecuteNonQuery();
Console.WriteLine("Table Created Successfully...");
conn.Close();
}
catch(Exception e)
{
Console.WriteLine("exception occured while creating table:" + e.Message + "\t" + e.GetType());
}
Console.ReadKey();
}
}
}
@Patrick is correct with what he said, but to answer your other questions a View will create itself in Memory, and depending on the type of Joins, Data and if there is any aggregation done, it could be a quite memory hungry View.
Stored procedures do all their processing either using Temp Hash Table e.g #tmpTable1 or in memory using @tmpTable1. Depending on what you want to tell it to do.
A Stored Procedure is like a Function, but is called Directly by its name. instead of Functions which are actually used inside a query itself.
Obviously most of the time Memory tables are faster, if you are not retrieveing alot of data.
If you looking for vertical LinearLayout Manager you can achieve smooth scrolling using a custom LinearSmoothScroller
:
import android.content.Context;
import android.graphics.PointF;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
public class SnappingLinearLayoutManager extends LinearLayoutManager {
public SnappingLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
int position) {
RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext());
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
private class TopSnappedSmoothScroller extends LinearSmoothScroller {
public TopSnappedSmoothScroller(Context context) {
super(context);
}
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return SnappingLinearLayoutManager.this
.computeScrollVectorForPosition(targetPosition);
}
@Override
protected int getVerticalSnapPreference() {
return SNAP_TO_START;
}
}
}
use an instance of the layoutmanager in recycle view and then calling recyclerView.smoothScrollToPosition(pos);
will smooth scroll to selected position to top of the recycler view
After adding an item to a list, you can replace it by writing
list[someIndex] = new MyClass();
You can modify an existing item in the list by writing
list[someIndex].SomeProperty = someValue;
EDIT: You can write
var index = list.FindIndex(c => c.Number == someTextBox.Text);
list[index] = new SomeClass(...);
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
// No need for the list
// List<string> list_lines = new List<string>(lines);
Parallel.ForEach(lines, line =>
{
//My Stuff
});
This will cause the lines to be parsed in parallel, within the loop. If you want a more detailed, less "reference oriented" introduction to the Parallel class, I wrote a series on the TPL which includes a section on Parallel.ForEach.
Refer to Automatically Wrap Text in Label. It describes how to create your own growing label.
Here is the full source taken from the above reference:
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
public class GrowLabel : Label {
private bool mGrowing;
public GrowLabel() {
this.AutoSize = false;
}
private void resizeLabel() {
if (mGrowing) return;
try {
mGrowing = true;
Size sz = new Size(this.Width, Int32.MaxValue);
sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
this.Height = sz.Height;
}
finally {
mGrowing = false;
}
}
protected override void OnTextChanged(EventArgs e) {
base.OnTextChanged(e);
resizeLabel();
}
protected override void OnFontChanged(EventArgs e) {
base.OnFontChanged(e);
resizeLabel();
}
protected override void OnSizeChanged(EventArgs e) {
base.OnSizeChanged(e);
resizeLabel();
}
}
Memcached client library was just recently released as stable. It is being used by digg ( was developed for digg by Andrei Zmievski, now no longer with digg) and implements much more of the memcached protocol than the older memcache client. The most important features that memcached has are:
All of this points were enough for me to switch to the newest client, and can tell you that it works like a charm. There is that external dependency on the libmemcached library, but have managed to install it nonetheless on Ubuntu and Mac OSX, so no problems there so far.
If you decide to update to the newer library, I suggest you update to the latest server version as well as it has some nice features as well. You will need to install libevent for it to compile, but on Ubuntu it wasn't much trouble.
I haven't seen any frameworks pick up the new memcached client thus far (although I don't keep track of them), but I presume Zend will get on board shortly.
Zend Framework 2 has an adapter for Memcached which can be found here
SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty.
The specific keys you have to set are below:
javax.net.ssl.keyStore- Location of the Java keystore file containing an application process's own certificate and private key. On Windows, the specified pathname must use forward slashes, /, in place of backslashes.
javax.net.ssl.keyStorePassword - Password to access the private key from the keystore file specified by javax.net.ssl.keyStore. This password is used twice: To unlock the keystore file (store password), and To decrypt the private key stored in the keystore (key password).
javax.net.ssl.trustStore - Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store). On Windows, the specified pathname must use forward slashes,
/
, in place of backslashes,\
.If a trust store location is not specified using this property, the SunJSSE implementation searches for and uses a keystore file in the following locations (in order):
$JAVA_HOME/lib/security/jssecacerts
$JAVA_HOME/lib/security/cacerts
javax.net.ssl.trustStorePassword - Password to unlock the keystore file (store password) specified by
javax.net.ssl.trustStore
.javax.net.ssl.trustStoreType - (Optional) For Java keystore file format, this property has the value jks (or JKS). You do not normally specify this property, because its default value is already jks.
javax.net.debug - To switch on logging for the SSL/TLS layer, set this property to ssl.
Post ICS i.e. Android 4+, the overriding of the HomeButton has been removed for security reasons, to enable the user exit in case the application turns out to be a malware.
Plus, it is not a really good practice to not let the user navigate away from the application. But, since you are making a lock screen application, what you can do is declare the activity as a Launcher , so that when the HomeButton is pressed it will simply restart your application and remain there itself (the users would notice nothing but a slight flicker in the screen).
You can go through the following link:
http://dharmendra4android.blogspot.in/2012/05/override-home-button-in-android.html
You can use the required
html attribute if you want:
@Html.TextBoxFor(m => m.ShortName,
new { @class = "form-control", placeholder = "short name", required="required"})
or you can use the RequiredAttribute class in .Net. With jQuery the RequiredAttribute
can Validate on the front end and server side. If you want to go the MVC route, I'd suggest reading Data annotations MVC3 Required attribute.
OR
You can get really advanced:
@{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = new Dictionary<string, object>(
Html.GetUnobtrusiveValidationAttributes(ViewData.TemplateInfo.HtmlFieldPrefix));
attributes.Add("class", "form-control");
attributes.Add("placeholder", "short name");
if (ViewData.ModelMetadata.ContainerType
.GetProperty(ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(RequiredAttribute), true)
.Select(a => a as RequiredAttribute)
.Any(a => a != null))
{
attributes.Add("required", "required");
}
@Html.TextBoxFor(m => m.ShortName, attributes)
}
or if you need it for multiple editor templates:
public static class ViewPageExtensions
{
public static IDictionary<string, object> GetAttributes(this WebViewPage instance)
{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = new Dictionary<string, object>(
instance.Html.GetUnobtrusiveValidationAttributes(
instance.ViewData.TemplateInfo.HtmlFieldPrefix));
if (ViewData.ModelMetadata.ContainerType
.GetProperty(ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(RequiredAttribute), true)
.Select(a => a as RequiredAttribute)
.Any(a => a != null))
{
attributes.Add("required", "required");
}
}
}
then in your templates:
@{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = this.GetAttributes();
attributes.Add("class", "form-control");
attributes.Add("placeholder", "short name");
@Html.TextBoxFor(m => m.ShortName, attributes)
}
Update 1 (for Tomas who is unfamilar with ViewData).
What's the difference between ViewData and ViewBag?
Excerpt:
So basically it (ViewBag) replaces magic strings:
ViewData["Foo"]
with magic properties:
ViewBag.Foo
Just to elaborate a bit on the meta-tag thing. I've heard a talk, where a statement was made, one should always insert the "no-sniff" meta tag in the html to prevent browser sniffing (just like OP did):
<meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" />
However, this is not a valid method for w3c compliant websites, the validator will raise an error:
Bad value text/html; charset=UTF-8; X-Content-Type-Options=nosniff for attribute content on element meta: The legacy encoding contained ;, which is not a valid character in an encoding name.
And there is no fixing this. To rightly turn off no-sniff, one has to go to the server settings and turn it off there. Because the "no-sniff" option is something from the HTTP header, not from the HTML file which is attached at the HTTP response.
To check if the no-sniff option is disabled, one can enable the developer console, networks tab and then inspect the HTTP response header:
Some practical uses for the [Serializable]
attribute:
BinaryFormatter
class in System.Runtime.Serialization.Formatters.BinaryClipboard.SetData()
- nonserialisable classes cannot be placed on the clipboard.MarshalByRefObject
) must be serialisable.These are the most common usage cases that I have come across.
I was also looking for the global .gitconfig
on my Windows machine and found this neat trick using git.
Do a: git config --global -e
and then, if you are lucky, you will get a text editor loaded with your global .gitconfig
file. Simply lookup the folder from there (or try a save as...), et voilà! :-)
I have looked at each of these solutions that also seem to work with one issue. Dark Mode and the background setting
The Background setting of the UITextField must match the background of the parent view or no line appears
So this will work on light mode To get to work in dark mode change the background color to black and it works Exclude back color and the line does not appear
let field = UITextField()
field.backgroundColor = UIColor.white
field.bottomBorderColor = UIColor.red
This ended up being the best solution for me
extension UITextField {
func addPadding() {
let paddingView = UIView(frame: CGRect(x:0, y:0, width: 10, height: self.frame.height))
self.leftView = paddingView
self.leftViewMode = .always
}
@IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: newValue!])
}
}
@IBInspectable var bottomBorderColor: UIColor? {
get {
return self.bottomBorderColor
}
set {
self.borderStyle = .none
self.layer.masksToBounds = false
self.layer.shadowColor = newValue?.cgColor
self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
self.layer.shadowOpacity = 1.0
self.layer.shadowRadius = 0.0
}
}
}
Why use java.awt.Robot when org.openqa.selenium.interactions.Actions.class would probably work fine? Just sayin.
Actions builder = new Actions(driver);
builder.keyDown(Keys.CONTROL)
.click(someElement)
.moveByOffset( 10, 25 );
.click(someOtherElement)
.keyUp(Keys.CONTROL).build().perform();
In Java 1.7+
Do not use "UTF-8" string, instead use Charset
type parameter:
import java.nio.charset.StandardCharsets
...
new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
I solved this problem using this command COMPOSER_MEMORY_LIMIT=-1
Example: COMPOSER_MEMORY_LIMIT=-1 composer requires larval/ui
Developed this method:
You NEED a table that has an unique value that can be ordered.
If you want rows 10,000 to 25,000 and your Table has 40,000 rows, first you need to get the starting point and total rows:
int start = 40000 - 10000;
int total = 25000 - 10000;
And then pass these by code to the query:
SELECT * FROM
(SELECT * FROM schema.mytable
ORDER BY userId DESC fetch first {start} rows only ) AS mini
ORDER BY mini.userId ASC fetch first {total} rows only
if you want to use Collections.fill(list, obj); in order to fill the list with a repeated object alternatively you can use
ArrayList<Integer> arr=new ArrayList<Integer>(Collections.nCopies(10, 0));
the line copies 10 times 0 in to your ArrayList
Both of the previous answers from Matt York and Cyberbolt are right.
Basic idea is here that you want to get some kind of File explorer in Sublime.
Approach:
1) With File -> New Folder -> Click on Desired folder and Hit Open
you will get new popup window in sublime which for me is very annoying
2) I use second option which is drag'n'drop from nautilus (a.k.a. Files) window. Simply drag'n'drop your file you want to explore from nautilus to sublime sidebar
. That way you stay in the same window and everything is cool.
Don't forget to enable View -> Sidebar -> Show Sidebar and drag'n'drop there from nautilus and of course run it with root privleges
. It works like charm
https://play.golang.org/p/JGZ7mN0-U-
for k, v := range m {
fmt.Printf("key[%s] value[%s]\n", k, v)
}
or
for k := range m {
fmt.Printf("key[%s] value[%s]\n", k, m[k])
}
Go language specs for for
statements specifies that the first value is the key, the second variable is the value, but doesn't have to be present.
problem is glibc, which is not part of apline base iamge.
After adding it worked for me :)
Here are the steps to get the glibc
apk --no-cache add ca-certificates wget
wget -q -O /etc/apk/keys/sgerrand.rsa.pub https://alpine-pkgs.sgerrand.com/sgerrand.rsa.pub
wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.28-r0/glibc-2.28-r0.apk
apk add glibc-2.28-r0.apk
.
(dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess
files, then they are probably in the root folder for the website.
If you are using a command line (terminal) to access, then they will only show up if you use:
ls -a
If you are using a GUI application, look for a setting to "show hidden files" or something similar.
If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):
cd /
find . -name ".htaccess"
This will list out any files it finds with that name.
With ECMAScript 6, you can use variable property names with the object literal syntax, like this:
var keyName = 'myKey';
var obj = {
[keyName]: 1
};
obj.myKey;//1
This syntax is available in the following newer browsers:
Edge 12+ (No IE support), FF34+, Chrome 44+, Opera 31+, Safari 7.1+
(https://kangax.github.io/compat-table/es6/)
You can add support to older browsers by using a transpiler such as babel. It is easy to transpile an entire project if you are using a module bundler such as rollup or webpack.
In cases where you are hosting a Wordpress site on Linux and have server access you can save some headaches by installing msmtp which allows you to send via smtp from the standard php mail() function. msmtp is a simpler alternative to postfix which requires a bit more configuration.
Here are the steps:
Install msmtp
sudo apt-get install msmtp-mta ca-certificates
Create a new configuration file:
sudo nano /etc/msmtprc
...with the following configuration information:
# Set defaults.
defaults
# Enable or disable TLS/SSL encryption.
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
# Set up a default account's settings.
account default
host <smtp.example.net>
port 587
auth on
user <[email protected]>
password <password>
from <[email protected]>
syslog LOG_MAIL
You need to replace the configuration data represented by everything within "<" and ">" (inclusive, remove these). For host/username/password, use your normal credentials for sending mail through your mail provider.
Tell PHP to use it
sudo nano /etc/php5/apache2/php.ini
Add this single line:
sendmail_path = /usr/bin/msmtp -t
Complete documention can be found here:
I imagine this like that:
<html>
<head>
<script>
var frame_loaded = 0;
function setFrameLoaded()
{
frame_loaded = 1;
alert("Iframe is loaded");
}
$('#click').click(function(){
if(frame_loaded == 1)
console.log('iframe loaded')
} else {
console.log('iframe not loaded')
}
})
</script>
</head>
<button id='click'>click me</button>
<iframe id='MainPopupIframe' onload='setFrameLoaded();' src='http://...' />...</iframe>
You can use File.WriteAllBytes
The accepted answer is wrong. GET
requests can indeed contain a body. This is the solution implemented by WordPress, as an example:
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );
EDIT: To clarify, the initial curl_setopt
is necessary in this instance, because libcurl will default the HTTP method to POST
when using CURLOPT_POSTFIELDS
(see documentation).
from IPython.display import display
display(df) # OR
print df.to_html()
After reading Paul's answer, I went on digging for more information on https://dev.mysql.com/doc/refman/5.7/en/query-log.html
I found a really useful code by a person. Here's the summary of the context.
(Note: The following code is not mine)
This script is an example to keep the table clean which will help you to reduce your table size. As after a day, there will be about 180k queries of log. ( in a file, it would be 30MB per day)
You need to add an additional column (event_unix) and then you can use this script to keep the log clean... it will update the timestamp into a Unix-timestamp, delete the logs older than 1 day and then update the event_time into Timestamp from event_unix... sounds a bit confusing, but it's working great.
Commands for the new column:
SET GLOBAL general_log = 'OFF';
RENAME TABLE general_log TO general_log_temp;
ALTER TABLE `general_log_temp`
ADD COLUMN `event_unix` int(10) NOT NULL AFTER `event_time`;
RENAME TABLE general_log_temp TO general_log;
SET GLOBAL general_log = 'ON';
Cleanup script:
SET GLOBAL general_log = 'OFF';
RENAME TABLE general_log TO general_log_temp;
UPDATE general_log_temp SET event_unix = UNIX_TIMESTAMP(event_time);
DELETE FROM `general_log_temp` WHERE `event_unix` < UNIX_TIMESTAMP(NOW()) - 86400;
UPDATE general_log_temp SET event_time = FROM_UNIXTIME(event_unix);
RENAME TABLE general_log_temp TO general_log;
SET GLOBAL general_log = 'ON';
Credit goes to Sebastian Kaiser (Original writer of the code).
Hope someone will find it useful as I did.
If you really need single quotes, apostrophes, you can use
html | numeric | hex
‘ | ‘ | ‘ // for the left/beginning single-quote and
’ | ’ | ’ // for the right/ending single-quote
Matt's answer is the right one for older Pythons and Kevin's the right answer for newer ones.
If you wish not to copy the function for silentremove
, this functionality is exposed in path.py as remove_p:
from path import Path
Path(filename).remove_p()
You can also use UNION like
SELECT user_fname ,
user_lname
FROM users
WHERE user_id = $_GET[id]
UNION
SELECT user_fname ,
user_lname
FROM users
WHERE user_parent_id = $_GET[id]
I had a similar thing to do. Using
// ini_set("output_buffering", 0); // off
ini_set("zlib.output_compression", 0); // off
ini_set("implicit_flush", 1); // on
did make the output flushing frequent in my case.
But I had to flush the output right at a particular point(in a loop that I run), so using both
ob_flush();
flush();
together worked for me.
I wasn't able to turn off "output_buffering" with ini_set(...), had to turn it directly in php.ini, phpinfo() shows its setting as "no value" when turned off, is that normal? .
Here's a way that allows for ties for the cut-off score.
author_count = Author.objects.count()
cut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]
top_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')
You may get more than 30 authors in top_authors this way and the min(30,author_count)
is there incase you have fewer than 30 authors.
You could try exe4j. This is effectively what we use through its cousin install4j.
<a class="navbar-brand" href="#" style="padding:0px;">
<img src="mylogo.png" style="height:100%;">
</a>
For including a text:
<a class="navbar-brand" href="#" style="padding:0px;">
<img src="mylogo.png" style="height:100%;display:inline-block;"><span>text</span>
</a>
methods = [(func, getattr(o, func)) for func in dir(o) if callable(getattr(o, func))]
gives an identical list as
methods = inspect.getmembers(o, predicate=inspect.ismethod)
does.
In Swift (version 2.0):
class func jsonStringWithJSONObject(jsonObject: AnyObject) throws -> String? {
let data: NSData? = try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: NSJSONWritingOptions.PrettyPrinted)
var jsonStr: String?
if data != nil {
jsonStr = String(data: data!, encoding: NSUTF8StringEncoding)
}
return jsonStr
}
When using JUnit 5 or above. You have to inject the class annotated with @Mock
in an @BeforeEach
setup.
Oracle JavaFX from Java SE supports only OS X (macOS), GNU/Linux and Microsoft Windows. On these platforms, JavaFX applications are typically run on JVM from Java SE or OpenJDK.
There is also a JavaFXPorts project, which is an open-source project sponsored by a third-party. It aims to port JavaFX library to Android and iOS.
On Android, this library can be used like any other Java library; the JVM bytecode is compiled to Dalvik bytecode. It's what people mean by saying that "Android runs Java".
On iOS, situation is a bit more complex, as neither Java SE nor OpenJDK supports Apple mobile devices. Till recently, the only sensible option was to use RoboVM ahead-of-time Java compiler for iOS. Unfortunately, on 15 April 2015, RoboVM project was shut down.
One possible alternative is Intel's Multi-OS Engine. Till recently, it was a proprietary technology, but on 11 August 2016 it was open-sourced. Although it can be possible to compile an iOS JavaFX app using JavaFXPorts' JavaFX implementation, there is no evidence for that so far. As you can see, the situation is dynamically changing, and this answer will be hopefully updated when new information is available.
With Windows Phone it's simple: there is no JavaFX support of any kind.
FROM openjdk:8-jdk-alpine
RUN apk update && apk add wget openssl lsof procps curl
RUN apk update
RUN mkdir -p /apps/agent
RUN mkdir -p /apps/lib
ADD ./app/agent /apps/agent
ADD ./app/lib /apps/lib
ADD ./app/* /apps/app/
RUN ls -lrt /apps/app/
CMD sh /apps/app/launch.sh
by using DockerFile, I'm copying agent and lib directories to /apps/agent,/apps/lib directories and bunch of files to target.
IF NOT USING THE SHORT HAND VERSION: Make sure the animation-fill-mode: forwards
is AFTER the animation declaration or it will not work...
animation-fill-mode: forwards;
animation-name: appear;
animation-duration: 1s;
animation-delay: 1s;
vs
animation-name: appear;
animation-duration: 1s;
animation-fill-mode: forwards;
animation-delay: 1s;
While you're waiting.. Curved corner (border-radius) cross browser
New Table...
Here is how you can do it using JavaScript:
//in your **popup.js** file just use this function
var input = document.getElementById("textSearch");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
alert("yes it works,I'm happy ");
}
});
_x000D_
<!--Let's say this is your html file-->
<!DOCTYPE html>
<html>
<body style="width: 500px">
<input placeholder="Enter the text and press enter" type="text" id="textSearch"/>
<script type="text/javascript" src="public/js/popup.js"></script>
</body>
</html>
_x000D_
I know this is a little late answer,
you can use if and else statements in ejs as follows
<% if (something) { %>
// Then do some operation
<% } else { %>
// Then do some operation
<% } %>
But there is another thing I want to emphasize is that if you use the code this way,
<% if (something) { %>
// Then do some operation
<% } %>
<% else { %>
// Then do some operation
<% } %>
It will produce an error.
Hope this will help to someone
This works, as long as you remove the height attribute from the table.
<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
<tr><td height='9px' bgcolor="#990000">Upper</td></tr>
<tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>
use this actiion
$(document).ready(function () {
var a = this.id;
alert (a);
});
Disclaimer, I work at Aptana. I would point out there are some nice features for JS that you might not get so easily elsewhere. One is plugin-level integration of JS libraries that provide CodeAssist, samples, snippets and easy inclusion of the libraries files into your project; we provide the plugins for many of the more commonly used libraries, including YUI, jQuery, Prototype, dojo and EXT JS.
Second, we have a server-side JavaScript engine called Jaxer that not only lets you run any of your JS code on the server but adds file, database and networking functionality so that you don't have to use a scripting language but can write the entire app in JS.
Make sure your app_offline.htm file is at least 512 bytes long. A zero-byte app_offline.htm will have no effect.
UPDATE: Newer versions of ASP.NET/IIS may behave better than when I first wrote this.
UPDATE 2: If you are using ASP.NET MVC, add the following to web.config:
<?xml version="1.0"?>
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
</configuration>
Here is my adaptation of Michael Soriano's tutorial. See below or in JSBin.
$(function() {_x000D_
var theImage = $('ul#ss li img');_x000D_
var theWidth = theImage.width();_x000D_
//wrap into mother div_x000D_
$('ul#ss').wrap('<div id="mother" />');_x000D_
//assign height width and overflow hidden to mother_x000D_
$('#mother').css({_x000D_
width: function() {_x000D_
return theWidth;_x000D_
},_x000D_
height: function() {_x000D_
return theImage.height();_x000D_
},_x000D_
position: 'relative',_x000D_
overflow: 'hidden'_x000D_
});_x000D_
//get total of image sizes and set as width for ul _x000D_
var totalWidth = theImage.length * theWidth;_x000D_
$('ul').css({_x000D_
width: function() {_x000D_
return totalWidth;_x000D_
}_x000D_
});_x000D_
_x000D_
var ss_timer = setInterval(function() {_x000D_
ss_next();_x000D_
}, 3000);_x000D_
_x000D_
function ss_next() {_x000D_
var a = $(".active");_x000D_
a.removeClass('active');_x000D_
_x000D_
if (a.hasClass('last')) {_x000D_
//last element -- loop_x000D_
a.parent('ul').animate({_x000D_
"margin-left": (0)_x000D_
}, 1000);_x000D_
a.siblings(":first").addClass('active');_x000D_
} else {_x000D_
a.parent('ul').animate({_x000D_
"margin-left": (-(a.index() + 1) * theWidth)_x000D_
}, 1000);_x000D_
a.next().addClass('active');_x000D_
}_x000D_
}_x000D_
_x000D_
// Cancel slideshow and move next manually on click_x000D_
$('ul#ss li img').on('click', function() {_x000D_
clearInterval(ss_timer);_x000D_
ss_next();_x000D_
});_x000D_
_x000D_
});
_x000D_
* {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
#ss {_x000D_
list-style: none;_x000D_
}_x000D_
#ss li {_x000D_
float: left;_x000D_
}_x000D_
#ss img {_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<ul id="ss">_x000D_
<li class="active">_x000D_
<img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado-colors.jpg">_x000D_
</li>_x000D_
<li>_x000D_
<img src="http://leemark.github.io/better-simple-slideshow/demo/img/monte-vista.jpg">_x000D_
</li>_x000D_
<li class="last">_x000D_
<img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado.jpg">_x000D_
</li>_x000D_
</ul>
_x000D_
You could try updating the table to get rid of these characters:
UPDATE dbo.[audit]
SET UserID = REPLACE(UserID, CHAR(0), '')
WHERE CHARINDEX(CHAR(0), UserID) > 0;
But then you'll also need to fix whatever is putting this bad data into the table in the first place. In the meantime perhaps try:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), ''))
FROM dbo.[audit];
But that is not a long term solution. Fix the data (and the data type while you're at it). If you can't fix the data type immediately, then you can quickly find the culprit by adding a check constraint:
ALTER TABLE dbo.[audit]
ADD CONSTRAINT do_not_allow_stupid_data
CHECK (CHARINDEX(CHAR(0), UserID) = 0);
EDIT
Ok, so that is definitely a 4-digit integer followed by six instances of CHAR(0). And the workaround I posted definitely works for me:
DECLARE @foo TABLE(UserID VARCHAR(32));
INSERT @foo SELECT 0x31353831000000000000;
-- this succeeds:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), '')) FROM @foo;
-- this fails:
SELECT CONVERT(INT, UserID) FROM @foo;
Please confirm that this code on its own (well, the first SELECT
, anyway) works for you. If it does then the error you are getting is from a different non-numeric character in a different row (and if it doesn't then perhaps you have a build where a particular bug hasn't been fixed). To try and narrow it down you can take random values from the following query and then loop through the characters:
SELECT UserID, CONVERT(VARBINARY(32), UserID)
FROM dbo.[audit]
WHERE UserID LIKE '%[^0-9]%';
So take a random row, and then paste the output into a query like this:
DECLARE @x VARCHAR(32), @i INT;
SET @x = CONVERT(VARCHAR(32), 0x...); -- paste the value here
SET @i = 1;
WHILE @i <= LEN(@x)
BEGIN
PRINT RTRIM(@i) + ' = ' + RTRIM(ASCII(SUBSTRING(@x, @i, 1)))
SET @i = @i + 1;
END
This may take some trial and error before you encounter a row that fails for some other reason than CHAR(0)
- since you can't really filter out the rows that contain CHAR(0)
because they could contain CHAR(0)
and CHAR(something else)
. For all we know you have values in the table like:
SELECT '15' + CHAR(9) + '23' + CHAR(0);
...which also can't be converted to an integer, whether you've replaced CHAR(0)
or not.
I know you don't want to hear it, but I am really glad this is painful for people, because now they have more war stories to push back when people make very poor decisions about data types.
button2.Enabled == true ;
must be button2.Enabled = true ;
.
You have a compare ==
where you should have an assign =
.
in my.cnf file , please change the following
## Instead of skip-networking the default is now to listen only on ## localhost which is more compatible and is not less secure. ## bind-address = 127.0.0.1
SQL is the actual language that as defined by the ISO and ANSI. Here is a link to the Wikipedia article. MySQL is a specific implementation of this standard. I believe Oracle bought the company that originally developed MySQL. Other companies also have their own implementations of the SQL standard.
use _x000D_
_x000D_
if(stripos($str,'job')){_x000D_
// do your work_x000D_
}
_x000D_
this is the answer of rakesh, but with support for arrays (which is quite common in forms):
plain javascript:
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
var addField = function( key, value ){
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", value );
form.appendChild(hiddenField);
};
for(var key in params) {
if(params.hasOwnProperty(key)) {
if( params[key] instanceof Array ){
for(var i = 0; i < params[key].length; i++){
addField( key, params[key][i] )
}
}
else{
addField( key, params[key] );
}
}
}
document.body.appendChild(form);
form.submit();
}
oh, and here's the jquery version: (slightly different code, but boils down to the same thing)
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
var form = $(document.createElement( "form" ))
.attr( {"method": method, "action": path} );
$.each( params, function(key,value){
$.each( value instanceof Array? value : [value], function(i,val){
$(document.createElement("input"))
.attr({ "type": "hidden", "name": key, "value": val })
.appendTo( form );
});
} );
form.appendTo( document.body ).submit();
}
If you use proxy, you will have to edit the Nuget.config file.
In Windows 7 and 10, this file is in the path:
C:\Users\YouUser\AppData\Roaming\NuGet.
Include the setting:
<config>
<add key = "http_proxy" value = "http://Youproxy:8080" />
<add key = "http_proxy.user" value = "YouProxyUser" />
</config>
Since your server already includes the sites-enabled
folder ( notice the include /etc/nginx/sites-enabled/*
line ), then you better use that.
Create a file inside /etc/nginx/sites-available
and call it whatever you want, I'll call it django
since it's a djanog server
sudo touch /etc/nginx/sites-available/django
Then create a symlink that points to it
sudo ln -s /etc/nginx/sites-available/django /etc/nginx/sites-enabled
Then edit that file with whatever file editor you use, vim
or nano
or whatever and create the server inside it
server {
# hostname or ip or multiple separated by spaces
server_name localhost example.com 192.168.1.1; #change to your setting
location / {
root /home/techcee/scrapbook/local/lib/python2.7/site-packages/django/__init__.pyc/;
}
}
Restart or reload nginx settings
sudo service nginx reload
Note I believe that your configuration like this probably won't work yet because you need to pass it to a fastcgi server or something, but at least this is how you could create a valid server
$("#select_box_id").children()[1].selected
This is another way of checking an option is selected or not in jquery. This will return Boolean (True or False).
[1] is index of select box option
One of the nice things about IntelliJ is that you don't need to use their annotations. You can write your own, or you can use those of whatever other tool you like. You're not even limited to a single type. If you're using two libraries that use different @NotNull annotations, you can tell IntelliJ to use both of them. To do this, go to "Configure Inspections", click on the "Constant Conditions & Exceptions" inspection, and hit the "Configure inspections" button. I use the Nullness Checker wherever I can, so I set up IntelliJ to use those annotations, but you can make it work with whatever other tool you want. (I have no opinion on the other tools because I've been using IntelliJ's inspections for years, and I love them.)
You must to download MySQLConnection NET from here.
Then you need add MySql.Data.DLL
to MSVisualStudio like this:
C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.12\Assemblies\v4.5.2
If you want to know more visit: enter link description here
To use in the code you must import the library:
using MySql.Data.MySqlClient;
An example with connectio to Mysql database (NO SSL MODE) by means of Click event:
using System;
using System.Windows;
using MySql.Data.MySqlClient;
namespace Deportes_WPF
{
public partial class Login : Window
{
private MySqlConnection connection;
private string server;
private string database;
private string user;
private string password;
private string port;
private string connectionString;
private string sslM;
public Login()
{
InitializeComponent();
server = "server_name";
database = "database_name";
user = "user_id";
password = "password";
port = "3306";
sslM = "none";
connectionString = String.Format("server={0};port={1};user id={2}; password={3}; database={4}; SslMode={5}", server, port, user, password, database, sslM);
connection = new MySqlConnection(connectionString);
}
private void conexion()
{
try
{
connection.Open();
MessageBox.Show("successful connection");
connection.Close();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message + connectionString);
}
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
conexion();
}
}
}
Reviewer the solution by this Checking the solution of this page, make the following solution I hope it works: Example:
Javascript:
var context = window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
var url =window.location.protocol+"//"+ window.location.host +context+"/bla/bla";
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxImage.Checked)
{
groupBoxImage.Show();
}
else if (!checkBoxImage.Checked)
{
groupBoxImage.Hide();
}
}
Short answer, no, there is no native support for private properties with ES6 classes.
But you could mimic that behaviour by not attaching the new properties to the object, but keeping them inside a class constructor, and use getters and setters to reach the hidden properties. Note that the getters and setters gets redefine on each new instance of the class.
ES6
class Person {
constructor(name) {
var _name = name
this.setName = function(name) { _name = name; }
this.getName = function() { return _name; }
}
}
ES5
function Person(name) {
var _name = name
this.setName = function(name) { _name = name; }
this.getName = function() { return _name; }
}
Old question but for a simple API and light-weight solution; you can use perfy which uses high-resolution real time (process.hrtime
) internally.
var perfy = require('perfy');
function end(label) {
return function (err, saved) {
console.log(err ? 'Error' : 'Saved');
console.log( perfy.end(label).time ); // <——— result: seconds.milliseconds
};
}
for (var i = 1; i < LIMIT; i++) {
var label = 'db-save-' + i;
perfy.start(label); // <——— start and mark time
db.users.save({ id: i, name: 'MongoUser [' + i + ']' }, end(label));
}
Note that each time perfy.end(label)
is called, that instance is auto-destroyed.
Disclosure: Wrote this module, inspired by D.Deriso's answer. Docs here.
commands
also works.
import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result
It works on linux, python 2.7.
I use Google Chart Tools https://developers.google.com/chart/ It's well documented and the charts look great. Being javascript, you can feed it json data via ajax.
in Unix:
new com.sun.security.auth.module.UnixSystem().getUsername()
in Windows:
new com.sun.security.auth.module.NTSystem().getName()
in Solaris:
new com.sun.security.auth.module.SolarisSystem().getUsername()
I had this problem even after setting the config properly. git config
My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).
As @Richard pointed out above, the onClick needs to have a capital 'C'.
$('#stop').click(function() {
$('next').attr('onClick','stopMoving()');
}
As of April 2018, Chrome (along with several other major browsers) now require the muted
attribute too.
Therefore, you should use
<video width="320" height="240" autoplay loop muted>
<source src="movie.mp4" type="video/mp4" />
</video>
Oddly it looks like the other two answers don't spell it out, and it's definitely worth saying:
i++
means 'tell me the value of i
, then increment'
++i
means 'increment i
, then tell me the value'
They are Pre-increment, post-increment operators. In both cases the variable is incremented, but if you were to take the value of both expressions in exactly the same cases, the result will differ.
You need to understand the difference between classes and objects. From the Java tutorial:
An object is a software bundle of related state and behavior
A class is a blueprint or prototype from which objects are created
You've defined the prototypes but done nothing with them. To use an object, you need to create it. In Java, we use the new
keyword.
new Date();
You will need to assign the object to a variable of the same type as the class the object was created from.
Date d = new Date();
Once you have a reference to the object you can interact with it
d.date("01", "12", "14");
The exception to this is static methods that belong to the class and are referenced through it
public class MyDate{
public static date(){ ... }
}
...
MyDate.date();
In case you aren't aware, Java already has a class for representing dates, you probably don't want to create your own.
Here's an answer I found online at this site Describes how to do the above1 You can find the answer at the bottom of the page. Basically, what you do is copy the row to be copied to a temporary table held in memory. You then change the Primary Key number using update. You then re-insert it into the target table. You then drop the table.
This is the code for it:
CREATE TEMPORARY TABLE
rescueteam
ENGINE=MEMORY SELECT * FROMfitnessreport4
WHERE rID=1;# 1 row affected. UPDATErescueteam
SET rID=Null WHERE rID=1;# 1 row affected.INSERT INTOfitnessreport4
SELECT * FROMrescueteam
;# 1 row affected. DROP TABLErescueteam
# MySQL returned an empty result set (i.e. zero
rows).
I created the temporary table rescueteam. I copied the row from my original table fitnessreport4. I then set the primary key for the row in the temporary table to null so that I can copy it back to the original table without getting a Duplicate Key error. I tried this code yesterday evening and it worked.
Just cause I don't see this bit of information in the answers above, the reason the code snippet originally posted doesn't work correctly is because the encodedBytes
variable is a byte[]
and not a String
value. If you pass the byte[]
to a new String()
as below, the code snippet works perfectly.
encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + new String(encodedBytes);
Just a small addition to Jeff Bowman's excellent answer, as I found this question when searching for a solution to one of my own problems:
If a call to a method matches more than one mock's when
trained calls, the order of the when
calls is important, and should be from the most wider to the most specific. Starting from one of Jeff's examples:
when(foo.quux(anyInt(), anyInt())).thenReturn(true);
when(foo.quux(anyInt(), eq(5))).thenReturn(false);
is the order that ensures the (probably) desired result:
foo.quux(3 /*any int*/, 8 /*any other int than 5*/) //returns true
foo.quux(2 /*any int*/, 5) //returns false
If you inverse the when calls then the result would always be true
.
>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')
Edit: Note that zip(*iterable)
is its own inverse:
>>> list(source_list) == zip(*zip(*source_list))
True
When unpacking into two lists, this becomes:
>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True
Addition suggested by rocksportrocker.
I was facing the same error and struggled with it for hours. I had a web API project which is using Newtonsoft.json and another UnitTest project for the web API project. The unit test project also needed the Newtonsoft.json reference. But on adding the link I was getting the above exception.
I finally resolved it by adding the below code snippet in the app.config of the unit test project:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
let canvas = document.getElementById('canvas');_x000D_
canvas.setAttribute('width', window.innerWidth);_x000D_
canvas.setAttribute('height', window.innerHeight);_x000D_
let ctx = canvas.getContext('2d');_x000D_
_x000D_
//Draw Canvas Fill mode_x000D_
ctx.fillStyle = 'blue';_x000D_
ctx.fillRect(0,0,canvas.width, canvas.height);
_x000D_
* { margin: 0; padding: 0; box-sizing: border-box; }_x000D_
body { overflow: hidden; }
_x000D_
<canvas id='canvas'></canvas>
_x000D_
set_time_limit(0);
$file = file_get_contents('path of your file');
file_put_contents('file.ext', $file);
I agree with pez and some here.
It seems obvious to me that "new" is self descriptive object creation, where the YUI pattern Greg Dean describes is completely obscured.
The possibility someone could write var bar = foo;
or var bar = baz();
where baz isn't an object creating method seems far more dangerous.
In addition, if you want to override all instances and not just that one special instance, this one might help.
function MyClass() {}
MyClass.prototype.myMethod = function() {
alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
MyClass.prototype.myMethod_original.call( this );
alert( "doing override");
};
myObj = new MyClass();
myObj.myMethod();
result:
doing original
doing override
use
python manage.py dumpdata
then look at the end you will find the user name
If you use the Date
property for DB Entities you will get exception:
"The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."
You can use something like this:
DateTime date = DateTime.Now.Date;
var result = from client in context.clients
where client.BirthDate >= date
&& client.BirthDate < date.AddDays(1)
select client;
Another workaround is using shortpath in windows:
c:\
dir program* /x
PROGRA~2
C:\PROGRA~2
is same as C:\Program Files (x86)
JAVA_HOME
replace path to :
C:\PROGRA~2\Java\jre7
This should work in windows 64 environment as it worked for me in win7 64bit version.
You will have to manually delete from the project explorer (your local machine hard drive), then delete the project in IntelliJ when it asks to re-open recent projects.
Use org.hibernate.annotations
for doing Cascade
, if the hibernate
and JPA
are used together , its somehow complaining on saving the child objects.
It is also interesting to compare the file of the current working revision with the same file of another revision.
You can do as follows:
$ svn diff -r34 file
You may use any of these 2 variants:
/^[A-Z]+$/i
/^[A-Za-z]+$/
to match an input string of ASCII alphabets.
[A-Za-z]
will match all the alphabets (both lowercase and uppercase).^
and $
will make sure that nothing but these alphabets will be matched.Code:
preg_match('/^[A-Z]+$/i', "abcAbc^Xyz", $m);
var_dump($m);
Output:
array(0) {
}
Test case is for OP's comment that he wants to match only if there are 1 or more alphabets present in the input. As you can see in the test case that matches failed because there was ^
in the input string abcAbc^Xyz
.
Note: Please note that the above answer only matches ASCII alphabets and doesn't match Unicode characters. If you want to match Unicode letters then use:
/^\p{L}+$/u
Here, \p{L}
matches any kind of letter from any language
document.getElementById('Id').value='new value';
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
You can open PDF in Google Docs Viewer by appending URL to:
http://docs.google.com/gview?embedded=true&url=<url of a supported doc>
This would open PDF in default browser or a WebView.
A list of supported formats is given here.
Another way round it would be to stop UAC then restart it. Create a CMD file with the following code;
Rem Stop UAC %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f rem force reboot Start ShutDown /R /F /T 30
You'll need to right click on the CMD file and use run as admin. once you have finished what you are doing restart UAC with the following code (no need to use run as admin this time);
%windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 1 /f
rem force reboot Start ShutDown /R /F /T 30
The down sides to using this method is have to right click and use run as admin to close UAC down and you have to reboot for it to take effect.
BTW there are several reasons why you would need to write to the forbidden areas...the first two that springs to mind would be to run a batch file to append host to prevent your browser going to dodgy sites or to copy license keys in a silent install.
Building on the answer by @CMS I have the following (in CoffeeScript which can easily be converted to JavaScript):
String::to_query = ->
[result, re, d] = [{}, /([^&=]+)=([^&]*)/g, decodeURIComponent]
while match = re.exec(if @.match /^\?/ then @.substring(1) else @)
result[d(match[1])] = d match[2]
result
You can easily grab what you need with:
location.search.to_query()['my_param']
The win here is an object-oriented interface (instead of functional) and it can be done on any string (not just location.search).
If you are already using a JavaScript library this function make already exist. For example here is Prototype's version
We Use:
@ContextConfiguration(locations="file:WebContent/WEB-INF/spitterMVC-servlet.xml")
the project is a eclipse dynamic web project, then the path is:
{project name}/WebContent/WEB-INF/spitterMVC-servlet.xml
The ZingChart library has an AngularJS directive that was built in-house. Features include:
Support from the development team
...
$scope.myJson = {
type : 'line',
series : [
{ values : [54,23,34,23,43] },{ values : [10,15,16,20,40] }
]
};
...
<zingchart id="myChart" zc-json="myJson" zc-height=500 zc-width=600></zingchart>
There is a full demo with code examples available.
I use this:
private void MainForm_Load(object sender, EventArgs e)
{
if (Settings.Instance.HideAtStartup)
{
BeginInvoke(new MethodInvoker(delegate
{
Hide();
}));
}
}
Obviously you have to change the if condition with yours.
with a form, just set method
to "post"
<form action="blah.php" method="post">
<input type="text" name="data" value="mydata" />
<input type="submit" />
</form>
You could have Flash call the function when it's done. I'm not sure what you mean by web services. I assume you have JavaScript code calling web services via Ajax, in which case you would know when they terminate. In the worst case, you could do a looping setTimeout
that would check every 100 ms or so.
And the check for whether or not a variable is defined can be just if (myVariable)
or safer: if(typeof myVariable == "undefined")
If your purpose is to matching with another string by converting in one pass, you can use str.casefold()
as well.
This is useful when you have non-ascii characters and matching with ascii versions(eg: maße vs masse).Though str.lower
or str.upper
fails in such cases, str.casefold()
will pass.
This is available in Python 3 and the idea is discussed in detail with the answer https://stackoverflow.com/a/31599276/4848659.
>>>str="Hello World";
>>>print(str.lower());
hello world
>>>print(str.upper());
HELLO WOLRD
>>>print(str.casefold());
hello world
hg update [-r REV]
If later you commit, you will effectively create a new branch. Then you might continue working only on this branch or eventually merge the existing one into it.
for me this is what worked...
I edited the ./bash_profile and added below command
export PATH="/usr/local/opt/openssl/bin:$PATH"
yield
basically makes an IEnumerable<T>
method behave similarly to a cooperatively (as opposed to preemptively) scheduled thread.
yield return
is like a thread calling a "schedule" or "sleep" function to give up control of the CPU. Just like a thread, the IEnumerable<T>
method regains controls at the point immediately afterward, with all local variables having the same values as they had before control was given up.
yield break
is like a thread reaching the end of its function and terminating.
People talk about a "state machine", but a state machine is all a "thread" really is. A thread has some state (I.e. values of local variables), and each time it is scheduled it takes some action(s) in order to reach a new state. The key point about yield
is that, unlike the operating system threads we're used to, the code that uses it is frozen in time until the iteration is manually advanced or terminated.
for mysqli connect;
<?php
$host = "host";
$user = "user";
$pass = "pss";
$database = "db_name";
$connect = new mysqli($host, $user, $pass, $database);
// Actual code starts here Dont forget to change db_name !!
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'db_name'
AND ENGINE = 'MyISAM'";
$rs = $connect->query($sql);
while($row = $rs->fetch_array())
{
$tbl = $row[0];
$sql = "ALTER TABLE `$tbl` ENGINE=INNODB";
$connect->query($sql);
} ?>
For intel drivers, there is also this method
Disable Vertical Synchronization (VSYNC)
The intel-driver uses Triple Buffering for vertical synchronization, this allows for full performance and avoids tearing. To turn vertical synchronization off (e.g. for benchmarking) use this .drirc in your home directory:
<device screen="0" driver="dri2">
<application name="Default">
<option name="vblank_mode" value="0"/>
</application>
</device>
i solved this problem by removing space between quotes and command value inside of array ,this is happened because container exited after started and no executable command present which to be run inside of container.
['sh', '-c', 'echo Hello Kubernetes! && sleep 3600']
I think you need something like:
var text= data.response.venue.tips.groups[0].items[1].text;
I was experiencing this error on Android 5.1.1
devices sending network requests using okhttp/4.0.0-RC1
. Setting header Content-Length: <sizeof response>
on the server side resolved the issue.
You need to use to_timestamp()
to convert your string to a proper timestamp
value:
to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
If your column is of type DATE
(which also supports seconds), you need to use to_date()
to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
To get this into a where
condition use the following:
select *
from TableA
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')
You never need to use to_timestamp()
on a column that is of type timestamp
.
I think you can use methods of the str
type to do this. There's no need for regular expressions:
def remove_prefix(text, prefix):
if text.startswith(prefix): # only modify the text if it starts with the prefix
text = text.replace(prefix, "", 1) # remove one instance of prefix
return text
In your case you would use two case staements, one for each value you want returned.
Packages and stored procedures in Oracle execute by default using the rights of the package/procedure OWNER, not the currently logged on user.
So if you call a package that creates a user for example, its the package owner, not the calling user that needs create user privilege. The caller just needs to have execute permission on the package.
If you would prefer that the package should be run using the calling user's permissions, then when creating the package you need to specify AUTHID CURRENT_USER
Oracle documentation "Invoker Rights vs Definer Rights" has more information http://docs.oracle.com/cd/A97630_01/appdev.920/a96624/08_subs.htm#18575
Hope this helps.
After an activity started, restarted (onRestart() happens before onStart()), or paused (onPause()), onResume() called. When the activity is in the state of onResume(), the activity is ready to be used by the app user.
I have studied the activity lifecycle a little bit, and here's my understanding of this topic: If you want to restart the activity (A) at the end of the execution of another, there could be a few different cases.
The other activity (B) has been paused and/or stopped or destroyed, and the activity A possibly had been paused (onPause()), in this case, activity A will call onResume()
The activity B has been paused and/or stopped or destroyed, the activity A possibly had been stopped (onStop()) due to memory thing, in this case, activity A will call onRestart() first, onStart() second, then onResume()
The activity B has been paused and/or stopped or destroyed, the activity A has been destroyed, the programmer can call onStart() manually to start the activity first, then onResume() because when an activity is in the destroyed status the activity has not started, and this happens before the activity being completely removed. If the activity is removed, the activity needs to be created again. Manually calling onStart() I think it's because if the activity not started and it is created, onStart() will be called after onCreate().
If you want to update data, make a data update function and put the function inside the onResume(). Or put a loadData function inside onResume()
It's better to understand the lifecycle with the help of the Activity lifecycle diagram.
Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/
But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing
-rw-r--r--@
thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:
-rw-r--rw-@
This did it. The message disappeared.
First step get container id:
docker ps
This will show you something like
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1170fe9e9460 localhost:5000/python:env-7e847468c4d73a0f35e9c5164046ad88 "./run_notebook.sh" 26 seconds ago Up 25 seconds 0.0.0.0:8989->9999/tcp SLURM_TASK-303337_0
1170fe9e9460
is the container id in this case.
Second, enter the docker :
docker exec -it [container_id] bash
so in the above case:
docker exec -it 1170fe9e9460 bash
In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]:
A B C D
1 0.319124 0.296653 0.138206 0.246017
2 0.376994 0.326481 0.230464 0.066062
3 0.036134 0.192954 0.430341 0.340571
Based on @vdegenne 's answer... how to strip:
Single trailing slash:
theString.replace(/\/$/, '');
Single or consecutive trailing slashes:
theString.replace(/\/+$/g, '');
Single leading slash:
theString.replace(/^\//, '');
Single or consecutive leading slashes:
theString.replace(/^\/+/g, '');
Single leading and trailing slashes:
theString.replace(/^\/|\/$/g, '')
Single or consecutive leading and trailing slashes:
theString.replace(/^\/+|\/+$/g, '')
To handle both slashes and backslashes, replace instances of \/
with [\\/]
I ran into this error using Doctrine DBAL QueryBuilder.
I created a query with QueryBuilder that uses column subselects, also created with QueryBuilder. The subselects were only created via $queryBuilder->getSQL()
and not executed. The error happened on creating the second subselect. By provisionally executing each subselect with $queryBuilder->execute()
before using $queryBuilder->getSQL()
, everything worked. It is as if the connection $queryBuilder->connection
remains in an invalid state for creating a new SQL before executing the currently prepared SQL, despite the new QueryBuilder instance on each subselect.
My solution was to write the subselects without QueryBuilder.
Simple 1-to-1 CSV to XLSX file conversion without enumerating/looping through the rows:
import pyexcel
sheet = pyexcel.get_sheet(file_name="myFile.csv", delimiter=",")
sheet.save_as("myFile.xlsx")
Notes:
I tried the other solutions, but I didn't find that c.NotebookApp.notebook_dir
setting in the config...
#jupyter_notebook_config.json
{
"NotebookApp": {
"nbserver_extensions": {
"jupyter_nbextensions_configurator": true
}
}
}
So, what I do is:
cd
into the directory where I want the notebooks and checkpoints
savedjupyter-lab
# ipython cell
import os
# change where notebooks are stored
os.chdir('/Users/me/Project')
os.getcwd()
Doing this with a CSS Grid is pretty easy. The trick is to set the grid's height to 100vw, then assign one of the rows to 75vw, and the remaining one (optional) to 1fr. This gives you, from what I assume is what you're after, a ratio-locked resizing container.
Example here: https://codesandbox.io/s/21r4z95p7j
You can even utilize the bottom gutter space if you so choose, simply by adding another "item".
Edit: StackOverflow's built-in code runner has some side effects. Pop over to the codesandbox link and you'll see the ratio in action.
body {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
background-color: #334;_x000D_
color: #eee;_x000D_
}_x000D_
_x000D_
.main {_x000D_
min-height: 100vh;_x000D_
min-width: 100vw;_x000D_
display: grid;_x000D_
grid-template-columns: 100%;_x000D_
grid-template-rows: 75vw 1fr;_x000D_
}_x000D_
_x000D_
.item {_x000D_
background-color: #558;_x000D_
padding: 2px;_x000D_
margin: 1px;_x000D_
}_x000D_
_x000D_
.item.dead {_x000D_
background-color: transparent;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<title>Parcel Sandbox</title>_x000D_
<meta charset="UTF-8" />_x000D_
<link rel="stylesheet" href="src/index.css" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="app">_x000D_
<div class="main">_x000D_
<div class="item">Item 1</div>_x000D_
<!-- <div class="item dead">Item 2 (dead area)</div> -->_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
fun hideKeyboard(activity: Activity) {
val view = activity.currentFocus
val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
assert(view != null)
methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
private fun showKeyboard(activity: Activity) {
val view = activity.currentFocus
val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
assert(view != null)
methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
public static void hideKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
assert methodManager != null && view != null;
methodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
private static void showKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
assert methodManager != null && view != null;
methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
I implemented a function similar to the momentjs method subtract.
function addDate(dt, amount, dateType) {
switch (dateType) {
case 'days':
return dt.setDate(dt.getDate() + amount) && dt;
case 'weeks':
return dt.setDate(dt.getDate() + (7 * amount)) && dt;
case 'months':
return dt.setMonth(dt.getMonth() + amount) && dt;
case 'years':
return dt.setFullYear( dt.getFullYear() + amount) && dt;
}
}
example:
let dt = new Date();
dt = addDate(dt, -1, 'months');// use -1 to subtract
export enum dateAmountType {
DAYS,
WEEKS,
MONTHS,
YEARS,
}
export function addDate(dt: Date, amount: number, dateType: dateAmountType): Date {
switch (dateType) {
case dateAmountType.DAYS:
return dt.setDate(dt.getDate() + amount) && dt;
case dateAmountType.WEEKS:
return dt.setDate(dt.getDate() + (7 * amount)) && dt;
case dateAmountType.MONTHS:
return dt.setMonth(dt.getMonth() + amount) && dt;
case dateAmountType.YEARS:
return dt.setFullYear( dt.getFullYear() + amount) && dt;
}
}
example:
let dt = new Date();
dt = addDate(dt, -1, 'months'); // use -1 to subtract
I also made some unit-tests for this function using Jasmine:
it('addDate() should works properly', () => {
for (const test of [
{ amount: 1, dateType: dateAmountType.DAYS, expect: '2020-04-13'},
{ amount: -1, dateType: dateAmountType.DAYS, expect: '2020-04-11'},
{ amount: 1, dateType: dateAmountType.WEEKS, expect: '2020-04-19'},
{ amount: -1, dateType: dateAmountType.WEEKS, expect: '2020-04-05'},
{ amount: 1, dateType: dateAmountType.MONTHS, expect: '2020-05-12'},
{ amount: -1, dateType: dateAmountType.MONTHS, expect: '2020-03-12'},
{ amount: 1, dateType: dateAmountType.YEARS, expect: '2021-04-12'},
{ amount: -1, dateType: dateAmountType.YEARS, expect: '2019-04-12'},
]) {
expect(formatDate(addDate(new Date('2020-04-12'), test.amount, test.dateType))).toBe(test.expect);
}
});
To use this test you need this function:
// get format date as 'YYYY-MM-DD'
export function formatDate(date: Date): string {
const d = new Date(date);
let month = '' + (d.getMonth() + 1);
let day = '' + d.getDate();
const year = d.getFullYear();
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
return [year, month, day].join('-');
}
Before talking about QueryParam & PathParam. Let's first understand the URL & its components. URL consists of endpoint + resource + queryParam/ PathParam.
For Example,
URL: https://app.orderservice.com/order?order=12345678
or
URL: https://app.orderservice.com/orders/12345678
where
endpoint: https://app.orderservice.com
resource: orders
queryParam: order=12345678
PathParam: 12345678
@QueryParam:
QueryParam is used when the requirement is to filter the request based on certain criteria/criterias. The criteria is specified with ? after the resource in URL. Multiple filter criterias can be specified in the queryParam by using & symbol.
For Example:
https://app.orderservice.com/orders?order=12345678 & customername=X
@PathParam:
PathParam is used when the requirement is to select the particular order based on guid/id. PathParam is the part of the resource in URL.
For Example:
https://app.orderservice.com/orders/12345678
brew install zlib
on OS X doesn't work anymore and instead prompts to install lzlib
. Installing that doesn't help.
Instead you install XCode Command line tools and that should install zlib
xcode-select --install