Just adding an example that worked fine for me:
$sqldb = [string]($sqldir) + '\bin\MySQLInstanceConfig.exe'
$myarg = '-i ConnectionUsage=DSS Port=3311 ServiceName=MySQL RootPassword= ' + $rootpw
Start-Process $sqldb -ArgumentList $myarg
Answers didn't help me to solve my problem, I couldn't find (and browse) the assemblies although I installed them using Microsoft's msi installer. For me, the excel assembly is located under C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\14.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll
If you are using SQL Express (which you are), then your login credentials are .\SQLEXPRESS
Here is the connectionString in the web config file which you can add:
<connectionStrings>
<add connectionString="Server=localhost\SQLEXPRESS;Database=yourDBName;Initial Catalog= yourDBName;Integrated Security=true" name="nametoCallBy" providerName="System.Data.SqlClient"/>
</connectionStrings>
Place is just above the system.web tag.
Then you can call it by:
connString = ConfigurationManager.ConnectionStrings["nametoCallBy"].ConnectionString;
try
.insertAfter()
here
$(content).insertAfter('#bla');
State machines can be very complex for a complex problem. They are also subject to unexpected bugs. They can turn into a nightmare if someone runs into a bug or needs to change the logic in the future. They are also difficult to follow and debug without the state diagram. Structured programming is much better (for example you would probably not use a state machine at mainline level). You can use structured programming even in interrupt context (which is where state machines are usually used). See this article "Macros to simulate multi-tasking/blocking code at interrupt level" found at codeproject.com.
I was able to do this by selecting "All" located under the "Keys" header from the left column
Then I clicked the plus button in the top right corner to add a new key
Enter a name for your key and check "APNs"
Then scroll down and select Continue. You will then be brought to a screen presenting you with the option to download your .p8 now or later. In my case, I was presented with a warning that it could only be downloaded once so keep the file safe.
I think the best that's possible in cross-browser JavaScript is window.print()
, which (in Firefox 3, for me) brings up the 'print' dialog and not the print preview dialog.
FYI, the print dialog is your computer's Print popup, what you get when you do Ctrl-p. The print preview is Firefox's own Preview window, and it has more options. It's what you get with Firefox Menu > Print...
It is not entirely clear what you want, but I would use numpy.random.randint:
import numpy.random as nprnd
import timeit
t1 = timeit.Timer('[random.randint(0, 1000) for r in xrange(10000)]', 'import random') # v1
### Change v2 so that it picks numbers in (0, 10000) and thus runs...
t2 = timeit.Timer('random.sample(range(10000), 10000)', 'import random') # v2
t3 = timeit.Timer('nprnd.randint(1000, size=10000)', 'import numpy.random as nprnd') # v3
print t1.timeit(1000)/1000
print t2.timeit(1000)/1000
print t3.timeit(1000)/1000
which gives on my machine:
0.0233682730198
0.00781716918945
0.000147947072983
Note that randint is very different from random.sample (in order for it to work in your case I had to change the 1,000 to 10,000 as one of the commentators pointed out -- if you really want them from 0 to 1,000 you could divide by 10).
And if you really don't care what distribution you are getting then it is possible that you either don't understand your problem very well, or random numbers -- with apologies if that sounds rude...
You must convert to List
as shown below:
String[] valores = hierarquia.split(".");
List<String> lista = Arrays.asList(valores);
String jpqlQuery = "SELECT a " +
"FROM AcessoScr a " +
"WHERE a.scr IN :param ";
Query query = getEntityManager().createQuery(jpqlQuery, AcessoScr.class);
query.setParameter("param", lista);
List<AcessoScr> acessos = query.getResultList();
Casting is not a mathematical operation and doesn't behave as such. Try
int y = (int)round(x);
It is worth noting that if you are returning server side data - you must supply the Data attribute even if there isn't any. It doesn't read the recordsTotal
or recordsFiltered
but relies on the count of the data object
Props: represents "read-only" data, that are immutable and refer to attributes from parents component.
State: represents mutable data, that ultimately affects what is rendered on the page and managed by internally by the component itself and change overtime commonly due to User input.
You are looking for the the MySQL functions FROM_UNIXTIME()
and UNIX_TIMESTAMP()
.
Use them in your SQL, e.g.:
mysql> SELECT UNIX_TIMESTAMP(NOW());
+-----------------------+
| UNIX_TIMESTAMP(NOW()) |
+-----------------------+
| 1311343579 |
+-----------------------+
1 row in set (0.00 sec)
mysql> SELECT FROM_UNIXTIME(1311343579);
+---------------------------+
| FROM_UNIXTIME(1311343579) |
+---------------------------+
| 2011-07-22 15:06:19 |
+---------------------------+
1 row in set (0.00 sec)
As user @aaracrr pointed out in a comment on another answer probably the best answer is to re-require the package with the same version constraint.
ie.
composer require vendor/package
or specifying a version constraint
composer require vendor/package:^1.0.0
It's because when you enter a number then press Enter, input.nextInt()
consumes only the number, not the "end of line". Primitive data types like int, double etc do not consume "end of line", therefore the "end of line" remains in buffer and When input.next()
executes, it consumes the "end of line" from buffer from the first input. That's why, your String sentence = scanner.next()
only consumes the "end of line" and does not wait to read from keyboard.
Tip: use scanner.nextLine()
instead of scanner.next()
because scanner.next()
does not read white spaces from the keyboard. (Truncate the string after giving some space from keyboard, only show string before space.)
Typically for a use case which involves a sequence of pages and in the final stage or page we post the data to the server. In this scenario we need to maintain the state. In the below snippet we maintain the state on the client side
As mentioned in the above post. The session is created using the factory recipe.
Client side session can be maintained using the value provider recipe as well.
Please refer to my post for the complete details. session-tracking-in-angularjs
Let's take an example of a shopping cart which we need to maintain across various pages / angularjs controller.
In typical shopping cart we buy products on various product / category pages and keep updating the cart. Here are the steps.
Here we create the custom injectable service having a cart inside using the "value provider recipe".
'use strict';
function Cart() {
return {
'cartId': '',
'cartItem': []
};
}
// custom service maintains the cart along with its behavior to clear itself , create new , delete Item or update cart
app.value('sessionService', {
cart: new Cart(),
clear: function () {
this.cart = new Cart();
// mechanism to create the cart id
this.cart.cartId = 1;
},
save: function (session) {
this.cart = session.cart;
},
updateCart: function (productId, productQty) {
this.cart.cartItem.push({
'productId': productId,
'productQty': productQty
});
},
//deleteItem and other cart operations function goes here...
});
The other queries are all going base on any ONE of the conditions qualifying and it will return a record... if you want to make sure the BOTH columns of table A are matched, you'll have to do something like...
select
tA.Col1,
tA.Col2,
tB.Val
from
TableA tA
join TableB tB
on ( tA.Col1 = tB.Col1 OR tA.Col1 = tB.Col2 )
AND ( tA.Col2 = tB.Col1 OR tA.Col2 = tB.Col2 )
CASE WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%'
THEN 'BP Medication' ELSE '' END AS [BP Medication]
The leading ', '
and trailing ','
are added so that you can handle the match regardless of where it is in the string (first entry, last entry, or anywhere in between).
That said, why are you storing data you want to search on as a comma-separated string? This violates all kinds of forms and best practices. You should consider normalizing your schema.
In addition: don't use 'single quotes'
as identifier delimiters; this syntax is deprecated. Use [square brackets]
(preferred) or "double quotes"
if you must. See "string literals as column aliases" here: http://msdn.microsoft.com/en-us/library/bb510662%28SQL.100%29.aspx
EDIT If you have multiple values, you can do this (you can't short-hand this with the other CASE
syntax variant or by using something like IN()
):
CASE
WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%'
WHEN ', ' + dbo.Table.Column +',' LIKE '%, amlodipine,%'
THEN 'BP Medication' ELSE '' END AS [BP Medication]
If you have more values, it might be worthwhile to use a split function, e.g.
USE tempdb;
GO
CREATE FUNCTION dbo.SplitStrings(@List NVARCHAR(MAX))
RETURNS TABLE
AS
RETURN ( SELECT DISTINCT Item FROM
( SELECT Item = x.i.value('(./text())[1]', 'nvarchar(max)')
FROM ( SELECT [XML] = CONVERT(XML, '<i>'
+ REPLACE(@List,',', '</i><i>') + '</i>').query('.')
) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
WHERE Item IS NOT NULL
);
GO
CREATE TABLE dbo.[Table](ID INT, [Column] VARCHAR(255));
GO
INSERT dbo.[Table] VALUES
(1,'lactulose, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(2,'lactulite, Lasix (furosemide), lactulose, propranolol, rabeprazole, sertraline,'),
(3,'lactulite, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(4,'lactulite, Lasix (furosemide), lactulose, amlodipine, rabeprazole, sertraline,');
SELECT t.ID
FROM dbo.[Table] AS t
INNER JOIN dbo.SplitStrings('lactulose,amlodipine') AS s
ON ', ' + t.[Column] + ',' LIKE '%, ' + s.Item + ',%'
GROUP BY t.ID;
GO
Results:
ID
----
1
2
4
Your Customer
class has to be discovered by CDI as a bean. For that you have two options:
Put a bean defining annotation on it. As @Model
is a stereotype it's why it does the trick. A qualifier like @Named
is not a bean defining annotation, reason why it doesn't work
Change the bean discovery mode in your bean archive from the default "annotated" to "all" by adding a beans.xml
file in your jar.
Keep in mind that @Named has only one usage : expose your bean to the UI. Other usages are for bad practice or compatibility with legacy framework.
Without needing to use Ctrl:
:%s/\r$//
Months are zero-based in Calendar. So 12 is interpreted as december + 1 month. Use
c.set(year, month - 1, day, 0, 0);
Using .format
from Python 2.6 and higher:
>>> print '{}{}{}{}'.format(*[7,7,7,7])
7777
>>> data = [7, 7, 7, 7] * 3
>>> print ('{}'*len(data)).format(*data)
777777777777777777777777
For Python 3:
>>> print(('{}'*len(data)).format(*data))
777777777777777777777777
Thanks so much Jason Pan for suggesting that method. The thread1 if statement is not atomic, so that while that statement executes, it's possible for thread2 to intrude on thread1, allowing non-reachable code to be reached. I've organized ideas from the prior posts into a complete demonstration program (below) that I ran with Python 2.7.
With some thoughtful analysis I'm sure we could gain further insight, but for now I think it's important to demonstrate what happens when non-atomic behavior meets threading.
# ThreadTest01.py - Demonstrates that if non-atomic actions on
# global variables are protected, task can intrude on each other.
from threading import Thread
import time
# global variable
a = 0; NN = 100
def thread1(threadname):
while True:
if a % 2 and not a % 2:
print("unreachable.")
# end of thread1
def thread2(threadname):
global a
for _ in range(NN):
a += 1
time.sleep(0.1)
# end of thread2
thread1 = Thread(target=thread1, args=("Thread1",))
thread2 = Thread(target=thread2, args=("Thread2",))
thread1.start()
thread2.start()
thread2.join()
# end of ThreadTest01.py
As predicted, in running the example, the "unreachable" code sometimes is actually reached, producing output.
Just to add, when I inserted a lock acquire/release pair into thread1 I found that the probability of having the "unreachable" message print was greatly reduced. To see the message I reduced the sleep time to 0.01 sec and increased NN to 1000.
With a lock acquire/release pair in thread1 I didn't expect to see the message at all, but it's there. After I inserted a lock acquire/release pair also into thread2, the message no longer appeared. In hind signt, the increment statement in thread2 probably also is non-atomic.
1.gcc version >= 5
2.CXXFLAGS += -std=c++14
3. #include <memory>
Solution in Swift 3:
button.setTitleColor(UIColor.red, for: .normal)
This will set the title color of button.
You could also use T-Regx library:
pattern('\D')->remove($c)
T-Regx also:
false
, null
or warnings)I haven't found this to work on, say Application objects. I have however had success with
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string rval = serializer.Serialize(myAppObj);
Using your example, you could do:
public void doit(A a) {
if(a instanceof B) {
// needs to cast to B to access draw2 which isn't present in A
// note that this is probably not a good OO-design, but that would
// be out-of-scope for this discussion :)
((B)a).draw2();
}
a.draw();
}
I use this function to calculate cpu usage. Hope it can help you.
private float readUsage() {
try {
RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
String load = reader.readLine();
String[] toks = load.split(" +"); // Split on one or more spaces
long idle1 = Long.parseLong(toks[4]);
long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
try {
Thread.sleep(360);
} catch (Exception e) {}
reader.seek(0);
load = reader.readLine();
reader.close();
toks = load.split(" +");
long idle2 = Long.parseLong(toks[4]);
long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));
} catch (IOException ex) {
ex.printStackTrace();
}
return 0;
}
You can do
a.divide(b, MathContext.DECIMAL128)
You can choose the number of bits you want either 32,64,128.
Check out this link :
Just for the fun of it, here are two ways that have not been explored:
substr($url, strpos($s, '/', 8), -4)
Or:
substr($s, strpos($s, '/', 8), -strlen($s) + strrpos($s, '.'))
Based on the idea that HTTP schemes http://
and https://
are at most 8 characters, so typically it suffices to find the first slash from the 9th position onwards. If the extension is always .php
the first code will work, otherwise the other one is required.
For a pure regular expression solution you can break the string down like this:
~^(?:[^:/?#]+:)?(?://[^/?#]*)?([^?#]*)~
^
The path portion would be inside the first memory group (i.e. index 1), indicated by the ^
in the line underneath the expression. Removing the extension can be done using pathinfo()
:
$parts = pathinfo($matches[1]);
echo $parts['dirname'] . '/' . $parts['filename'];
You can also tweak the expression to this:
([^?#]*?)(?:\.[^?#]*)?(?:\?|$)
This expression is not very optimal though, because it has some back tracking in it. In the end I would go for something less custom:
$parts = pathinfo(parse_url($url, PHP_URL_PATH));
echo $parts['dirname'] . '/' . $parts['filename'];
if(n==1 || n==0){
return n;
}else{
return fib(n-1) + fib(n-2);
}
However, using recursion to get fibonacci number is bad practice, because function is called about 8.5 times than received number. E.g. to get fibonacci number of 30 (1346269) - function is called 7049122 times!
You can do this with the use of Ascii integers. Put this code in the Textbox's Keypress event. e.KeyChar
represents the key that's pressed. And the the built-in function Asc()
converts it into its Ascii integer.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
'97 - 122 = Ascii codes for simple letters
'65 - 90 = Ascii codes for capital letters
'48 - 57 = Ascii codes for numbers
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
It is posible. My android device version is 4.0.4 and android.os.Build.VERSION.SDK_INT is 15
I have 3 spinners
Spinner c_fruit=(Spinner) findViewById(R.id.fruits);
Spinner c_vegetable=(Spinner) findViewById(R.id.vegetables);
Spinner c_beverage=(Spinner) findViewById(R.id.beverages);
And also I have a Async-Tack class.
Here is my spinner loading code
RequestSend reqs_fruit = new RequestSend(this);
reqs_fruit.where="Get_fruit_List";
reqs_fruit.title="Loading fruit";
reqs_fruit.execute();
RequestSend reqs_vegetable = new RequestSend(this);
reqs_vegetable.where="Get_vegetable_List";
reqs_vegetable.title="Loading vegetable";
reqs_vegetable.execute();
RequestSend reqs_beverage = new RequestSend(this);
reqs_beverage.where="Get_beverage_List";
reqs_beverage.title="Loading beverage";
reqs_beverage.execute();
This is working perfectly. One by one my spinners loaded. I didn't user executeOnExecutor.
Here is my Async-task class
public class RequestSend extends AsyncTask<String, String, String > {
private ProgressDialog dialog = null;
public Spinner spin;
public String where;
public String title;
Context con;
Activity activity;
String[] items;
public RequestSend(Context activityContext) {
con = activityContext;
dialog = new ProgressDialog(activityContext);
this.activity = activityContext;
}
@Override
protected void onPostExecute(String result) {
try {
ArrayAdapter<String> adapter = new ArrayAdapter<String> (activity, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
} catch (NullPointerException e) {
Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
super.onPostExecute(result);
if (dialog != null)
dialog.dismiss();
}
protected void onPreExecute() {
super.onPreExecute();
dialog.setTitle(title);
dialog.setMessage("Wait...");
dialog.setCancelable(false);
dialog.show();
}
@Override
protected String doInBackground(String... Strings) {
try {
Send_Request();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void Send_Request() throws JSONException {
try {
String DataSendingTo = "http://www.example.com/AppRequest/" + where;
//HttpClient
HttpClient httpClient = new DefaultHttpClient();
//Post header
HttpPost httpPost = new HttpPost(DataSendingTo);
//Adding data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("authorized","001"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line) ;
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
items = new String[finalResult.length()];
// looping through All details and store in public String array
for(int i = 0; i < finalResult.length(); i++) {
JSONObject c = finalResult.getJSONObject(i);
items[i]=c.getString("data_name");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have a list of color names in range A2:A8, in column B I want to extract a distinct list of color names.
Follow the below given steps:
=IF(COUNTIF(A$2:A2,A2)=1,A2,””)
Everytime you run sys.showModal function increment z-index and set it to your new modal.
function system() {
this.modalIndex = 2000;
this.showModal = function (selector) {
this.modalIndex++;
$(selector).modal({
backdrop: 'static',
keyboard: true
});
$(selector).modal('show');
$(selector).css('z-index', this.modalIndex );
}
}
var sys = new system();
sys.showModal('#myModal1');
sys.showModal('#myModal2');
All of these answers appear to be incomplete and/or kludges. Looking at the RestTemplate interface, it sure looks like it is intended to have a ClientHttpRequestFactory
injected into it, and then that requestFactory will be used to create the request, including any customizations of headers, body, and request params.
You either need a universal ClientHttpRequestFactory
to inject into a single shared RestTemplate
or else you need to get a new template instance via new RestTemplate(myHttpRequestFactory)
.
Unfortunately, it looks somewhat non-trivial to create such a factory, even when you just want to set a single Authorization header, which is pretty frustrating considering what a common requirement that likely is, but at least it allows easy use if, for example, your Authorization header can be created from data contained in a Spring-Security Authorization
object, then you can create a factory that sets the outgoing AuthorizationHeader on every request by doing SecurityContextHolder.getContext().getAuthorization()
and then populating the header, with null checks as appropriate. Now all outbound rest calls made with that RestTemplate will have the correct Authorization header.
Without more emphasis placed on the HttpClientFactory mechanism, providing simple-to-overload base classes for common cases like adding a single header to requests, most of the nice convenience methods of RestTemplate
end up being a waste of time, since they can only rarely be used.
I'd like to see something simple like this made available
@Configuration
public class MyConfig {
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate(new AbstractHeaderRewritingHttpClientFactory() {
@Override
public HttpHeaders modifyHeaders(HttpHeaders headers) {
headers.addHeader("Authorization", computeAuthString());
return headers;
}
public String computeAuthString() {
// do something better than this, but you get the idea
return SecurityContextHolder.getContext().getAuthorization().getCredential();
}
});
}
}
At the moment, the interface of the available ClientHttpRequestFactory's are harder to interact with than that. Even better would be an abstract wrapper for existing factory implementations which makes them look like a simpler object like AbstractHeaderRewritingRequestFactory for the purposes of replacing just that one piece of functionality. Right now, they are very general purpose such that even writing those wrappers is a complex piece of research.
Qt provides the simplest API
const char *qPrintable(const QString &str)
const char *qUtf8Printable(const QString &str)
If you want non-const data pointer use
str.toLocal8Bit().data()
str.toUtf8().data()
Here are two WORKAROUNDS to the problem of triggering downloads from the client only. In later browsers you should look at "blob"
1. Drag and drop the table
Did you know you can simply DRAG your table into excel?
Here is how to select the table to either cut and past or drag
Select a complete table with Javascript (to be copied to clipboard)
2. create a popup page from your div
Although it will not produce a save dialog, if the resulting popup is saved with extension .csv, it will be treated correctly by Excel.
The string could be
w.document.write("row1.1\trow1.2\trow1.3\nrow2.1\trow2.2\trow2.3");
e.g. tab-delimited with a linefeed for the lines.
There are plugins that will create the string for you - such as http://plugins.jquery.com/project/table2csv
var w = window.open('','csvWindow'); // popup, may be blocked though
// the following line does not actually do anything interesting with the
// parameter given in current browsers, but really should have.
// Maybe in some browser it will. It does not hurt anyway to give the mime type
w.document.open("text/csv");
w.document.write(csvstring); // the csv string from for example a jquery plugin
w.document.close();
DISCLAIMER: These are workarounds, and does not fully answer the question which currently has the answer for most browser: not possible on the client only
If can deviate a little from the straight path of DataTable -> SQL table, it can also be done via a list of objects:
1) DataTable -> Generic list of objects
public static DataTable ConvertTo<T>(IList<T> list)
{
DataTable table = CreateTable<T>();
Type entityType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
table.Rows.Add(row);
}
return table;
}
Source and more details can be found here. Missing properties will remain to their default values (0 for int
s, null for reference types etc.)
2) Push the objects into the database
One way is to use EntityFramework.BulkInsert
extension. An EF datacontext is required, though.
It generates the BULK INSERT command required for fast insert (user defined table type solution is much slower than this).
Although not the straight method, it helps constructing a base of working with list of objects instead of DataTable
s which seems to be much more memory efficient.
queryString = "SELECT name FROM user WHERE id=" & Worksheets("Sheet1").Range("D4").Value
From: http://nginx.org/r/large_client_header_buffers
Syntax:
large_client_header_buffers
number
size
;
Default:large_client_header_buffers 4 8k;
Context: http, serverSets the maximum
number
andsize
of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.
so you need to change the size parameter at the end of that line to something bigger for your needs.
Anyone interested in doing this should read the documentation of the Django Sessions framework. It stores a session ID in the user's cookies, but maps all the cookies-like data to your database. This is an improvement on the typical cookies-based workflow for HTTP requests.
Here is an example with a Django view ...
def homepage(request):
request.session.setdefault('how_many_visits', 0)
request.session['how_many_visits'] += 1
print(request.session['how_many_visits'])
return render(request, 'home.html', {})
If you keep visiting the page over and over, you'll see the value start incrementing up from 1 until you clear your cookies, visit on a new browser, go incognito, or do anything else that sidesteps Django's Session ID cookie.
Using dplyr
and tidyr
:
library(dplyr)
library(tidyr)
df <- as_data_frame(mat) %>% # convert the matrix to a data frame
gather(name, val, C_0:C_1) %>% # convert the data frame from wide to long
select(name, time, val) # reorder the columns
df
# A tibble: 6 x 3
name time val
<chr> <dbl> <dbl>
1 C_0 0.0 0.1
2 C_0 0.5 0.2
3 C_0 1.0 0.3
4 C_1 0.0 0.3
5 C_1 0.5 0.4
6 C_1 1.0 0.5
this is to disable dropdown2 , dropdown 3 if you select the option from dropdown1 that has the value 15
$("#dropdown1").change(function(){
if ( $(this).val()!= "15" ) {
$("#dropdown2").attr("disabled",true);
$("#dropdown13").attr("disabled",true);
}
I got this issue when i replaced old hibernate-core library with hibernate-core-5.2.12. However all my configuration was ok. And i fixed this issue by creating sessionfactory this way:
private static SessionFactory buildsSessionFactory() {
try {
if (sessionFactory == null) {
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure("/hibernate.cfg.xml").build();
Metadata metaData = new MetadataSources(standardRegistry)
.getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
}
return sessionFactory;
} catch (Throwable th) {
System.err.println("Enitial SessionFactory creation failed" + th);
throw new ExceptionInInitializerError(th);
}
}
Hope it helps someone
In case anyone encountering the same issue, please uninstall scipy and install scipy==1.1.0
$ pip uninstall scipy
$ pip install scipy==1.1.0
The img tag has a background property just like any other. If you have a white PNG with a transparent shape, like a stencil, then you can do this:
<img src= 'stencil.png' style= 'background-color: red'>
Try to test and initialize your arrays before you use them :
if( !isset($catagory[$i]) ) $catagory[$i] = '' ;
if( !isset($task[$i]) ) $task[$i] = '' ;
if( !isset($fullText[$i]) ) $fullText[$i] = '' ;
if( !isset($dueDate[$i]) ) $dueDate[$i] = '' ;
if( !isset($empId[$i]) ) $empId[$i] = '' ;
If $catagory[$i]
doesn't exist, you create (Uninitialized) one ... that's all ;
=> PHP try to read on your table in the address $i
, but at this address, there's nothing, this address doesn't exist => PHP return you a notice, and it put nothing to you string.
So you code is not very clean, it takes you some resources that down you server's performance (just a very little).
Take care about your MySQL tables default values
if( !isset($dueDate[$i]) ) $dueDate[$i] = '0000-00-00 00:00:00' ;
or
if( !isset($dueDate[$i]) ) $dueDate[$i] = 'NULL' ;
Maybe a shorter version, would be easier to understand?
jQuery("#btn").on('click', function() {_x000D_
var $txt = jQuery("#txt");_x000D_
var caretPos = $txt[0].selectionStart;_x000D_
var textAreaTxt = $txt.val();_x000D_
var txtToAdd = "stuff";_x000D_
$txt.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<textarea id="txt" rows="15" cols="70">There is some text here.</textarea>_x000D_
<input type="button" id="btn" value="OK" />
_x000D_
I wrote this in response to How to add a text to a textbox from the current position of the pointer with jquery?
You can always make simple xsd schema for 'packages.config' to get rid of this warning. To do this, create file named "packages.xsd":
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
targetNamespace="urn:packages" xmlns="urn:packages">
<xs:element name="packages">
<xs:complexType>
<xs:sequence>
<xs:element name="package" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="id" type="xs:string" use="required" />
<xs:attribute name="version" type="xs:string" use="required" />
<xs:attribute name="targetFramework" type="xs:string" use="optional" />
<xs:attribute name="allowedVersions" type="xs:string" use="optional" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Location of this file (two options)
packages.xsd
across multiple projects, move it to the Visual Studio Schemas folder (the path may slightly differ, it's D:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas
for me).Then, edit <packages>
tag in packages.config
file (add xmlns
attribute):
<packages xmlns="urn:packages">
Now the warning should disappear (even if packages.config file is open in Visual Studio).
The mysql_
functions:
Try this:
$.ajax({
type: 'get',
url: 'manageproducts.do',
data: 'option=1',
success: function(data) {
availableProductNames = data.split(",");
alert(availableProductNames);
}
});
Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.
Suppose you have two lists:
Id Value
1 A
2 B
3 C
Id ChildValue
1 a1
1 a2
1 a3
2 b1
2 b2
When you Join
the two lists on the Id
field the result will be:
Value ChildValue
A a1
A a2
A a3
B b1
B b2
When you GroupJoin
the two lists on the Id
field the result will be:
Value ChildValues
A [a1, a2, a3]
B [b1, b2]
C []
So Join
produces a flat (tabular) result of parent and child values.
GroupJoin
produces a list of entries in the first list, each with a group of joined entries in the second list.
That's why Join
is the equivalent of INNER JOIN
in SQL: there are no entries for C
. While GroupJoin
is the equivalent of OUTER JOIN
: C
is in the result set, but with an empty list of related entries (in an SQL result set there would be a row C - null
).
So let the two lists be IEnumerable<Parent>
and IEnumerable<Child>
respectively. (In case of Linq to Entities: IQueryable<T>
).
Join
syntax would be
from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }
returning an IEnumerable<X>
where X is an anonymous type with two properties, Value
and ChildValue
. This query syntax uses the Join
method under the hood.
GroupJoin
syntax would be
from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }
returning an IEnumerable<Y>
where Y is an anonymous type consisting of one property of type Parent
and a property of type IEnumerable<Child>
. This query syntax uses the GroupJoin
method under the hood.
We could just do select g
in the latter query, which would select an IEnumerable<IEnumerable<Child>>
, say a list of lists. In many cases the select with the parent included is more useful.
As said, the statement ...
from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }
... produces a list of parents with child groups. This can be turned into a flat list of parent-child pairs by two small additions:
from p in parents
join c in children on p.Id equals c.Id into g // <= into
from c in g.DefaultIfEmpty() // <= flattens the groups
select new { Parent = p.Value, Child = c?.ChildValue }
The result is similar to
Value Child
A a1
A a2
A a3
B b1
B b2
C (null)
Note that the range variable c
is reused in the above statement. Doing this, any join
statement can simply be converted to an outer join
by adding the equivalent of into g from c in g.DefaultIfEmpty()
to an existing join
statement.
This is where query (or comprehensive) syntax shines. Method (or fluent) syntax shows what really happens, but it's hard to write:
parents.GroupJoin(children, p => p.Id, c => c.Id, (p, c) => new { p, c })
.SelectMany(x => x.c.DefaultIfEmpty(), (x,c) => new { x.p.Value, c?.ChildValue } )
So a flat outer join
in LINQ is a GroupJoin
, flattened by SelectMany
.
Suppose the list of parents is a bit longer. Some UI produces a list of selected parents as Id
values in a fixed order. Let's use:
var ids = new[] { 3,7,2,4 };
Now the selected parents must be filtered from the parents list in this exact order.
If we do ...
var result = parents.Where(p => ids.Contains(p.Id));
... the order of parents
will determine the result. If the parents are ordered by Id
, the result will be parents 2, 3, 4, 7. Not good. However, we can also use join
to filter the list. And by using ids
as first list, the order will be preserved:
from id in ids
join p in parents on id equals p.Id
select p
The result is parents 3, 7, 2, 4.
You can create a directory with PHP using the mkdir() function.
mkdir("/path/to/my/dir", 0700);
You can use fopen() to create a file inside that directory with the use of the mode w
.
fopen('myfile.txt', 'w');
w : Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
For people just stumbling upon this now, I resolved an error of this type that was thrown with all the references and using statements placed properly. There's evidently some confusion with substituting in a function that returns DataTable instead of calling it on a declared DataTable. For example:
This worked for me:
DataTable dt = SomeObject.ReturnsDataTable();
List<string> ls = dt.AsEnumerable().Select(dr => dr["name"].ToString()).ToList<string>();
But this didn't:
List<string> ls = SomeObject.ReturnsDataTable().AsEnumerable().Select(dr => dr["name"].ToString()).ToList<string>();
I'm still not 100% sure why, but if anyone is frustrated by an error of this type, give this a try.
Quick fix. Create whole structure tr > td > button; then find button inside; attach event on it; end filtering of chain and at the and insert it into dom.
$("#myButton").click(function () {
var test = $('<tr><td><button>Test</button></td></tr>').find('button').click(function () {
alert('hi');
}).end();
$("#nodeAttributeHeader").attr('style', 'display: table-row;');
$("#addNodeTable tr:last").before(test);
});
You can try something like this:
long x = somevalue;
double y = Double.longBitsToDouble(x);
Aggregating with $lookup
and subsequent $group
is pretty cumbersome, so if (and that's a medium if) you're using node & Mongoose or a supporting library with some hints in the schema, you could use a .populate()
to fetch those documents:
var mongoose = require("mongoose"),
Schema = mongoose.Schema;
var productSchema = Schema({ ... });
var orderSchema = Schema({
_id : Number,
products: [ { type: Schema.Types.ObjectId, ref: "Product" } ]
});
var Product = mongoose.model("Product", productSchema);
var Order = mongoose.model("Order", orderSchema);
...
Order
.find(...)
.populate("products")
...
Why not this way:
Public Sub Init(myArguments)
instead of Private Sub Class_Initialize()
Dim myInstance As New myClass: myInstance.Init myArguments
get into similar problem while working on my MSc project, it seems that Daye's answer mistakenly reported "no fix" while the device stays in a static location. I've modified the solution just a little bit which seems to work fine for me in a static location. I don't how would it affect the battery as it is not my main concern, but here's how i did it by re-requesting location updates when a fix has timed out.
private class MyGPSListener implements GpsStatus.Listener {
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
if (Global.getInstance().currentGPSLocation != null)
{
if((SystemClock.elapsedRealtime() - mLastLocationMillis) < 20000)
{
if (!hasGPSFix)
Log.i("GPS","Fix Acquired");
hasGPSFix = true;
}
else
{
if (hasGPSFix)
{
Log.i("GPS","Fix Lost (expired)");
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
}
hasGPSFix = false;
}
}
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
Log.i("GPS", "First Fix/ Refix");
hasGPSFix = true;
break;
case GpsStatus.GPS_EVENT_STARTED:
Log.i("GPS", "Started!");
break;
case GpsStatus.GPS_EVENT_STOPPED:
Log.i("GPS", "Stopped");
break;
}
}
}
This worked for me:
$get("isAgeSelected ").checked == true
Where isAgeSelected
is the id of the control.
Also, @karim79's answer works fine. I am not sure what I missed at the time I tested it.
Note, this is answer uses Microsoft Ajax, not jQuery
SELECT *
FROM Customer
WHERE (I.IsClose=@ISClose OR @ISClose is NULL)
AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )
AND (isnull(@Value,1) <> 2
OR I.RecurringCharge = @Total
OR @Total is NULL )
AND (isnull(@Value,2) <> 3
OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
OR @Total is NULL )
Basically, your condition was
if (@Value=2)
TEST FOR => (I.RecurringCharge=@Total or @Total is NULL )
flipped around,
AND (isnull(@Value,1) <> 2 -- A
OR I.RecurringCharge = @Total -- B
OR @Total is NULL ) -- C
When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2
, which is the original intention.
Rename multiple file extensions:
You want to change ringtone1.mp3
, ringtone2.mp3
to ringtone1.wav
, ringtone2.wav
Here is how to do that: I am in d drive on command prompt (CMD) so I use:
d:\>ren *.* *.wav
This is just an example of file extensions, you can use any type of file extension like WAV, MP3, JPG, GIF, bmp, PDF, DOC, DOCX, TXT this depends on what your operating system.
And, since you have thousands of files, make sure to wait until the cursor starts blinking again indicating that it's done working.
You can think of the HEAD as the "current branch". When you switch branches with git checkout
, the HEAD revision changes to point to the tip of the new branch.
You can see what HEAD points to by doing:
cat .git/HEAD
In my case, the output is:
$ cat .git/HEAD
ref: refs/heads/master
It is possible for HEAD to refer to a specific revision that is not associated with a branch name. This situation is called a detached HEAD.
awk
awk '{gsub(/two.*/,"")}1' file
Ruby
ruby -ne 'print $_.gsub(/two.*/,"")' file
One option is to use the filetype
package.
Installation
python -m pip install filetype
Advantages
Example
filetype >= 1.0.7
import filetype
filename = "/path/to/file.jpg"
if filetype.is_image(filename):
print(f"{filename} is a valid image...")
elif filetype.is_video(filename):
print(f"{filename} is a valid video...")
filetype <= 1.0.6
import filetype
filename = "/path/to/file.jpg"
if filetype.image(filename):
print(f"{filename} is a valid image...")
elif filetype.video(filename):
print(f"{filename} is a valid video...")
Additional information on the official repo: https://github.com/h2non/filetype.py
Try this.
git clone -b <branch_name> --recursive <remote> <directory>
If you have added the submodule in a branch make sure that you add it to the clone command.
@Kwang-Chun Kang Thanks Kang a lot! I found the solution is working and very helpful, it really save my day. For me I am trying to create a React.js component that convert *.xlsx to json object when user upload the excel file to a html input tag. First I need to install XLSX package with:
npm install xlsx --save
Then in my component code, import with:
import XLSX from 'xlsx'
The component UI should look like this:
<input
accept=".xlsx"
type="file"
onChange={this.fileReader}
/>
It calls a function fileReader(), which is exactly same as the solution provided. To learn more about fileReader API, I found this blog to be helpful: https://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
If you need to add multiple key=>value, then try this.
$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));
You can use nested.
There are tow function one is openTab()
and another is closeMobileMenue()
, Firstly we call openTab()
and call another function inside closeMobileMenue()
.
function openTab() {
window.open('https://play.google.com/store/apps/details?id=com.drishya');
closeMobileMenue() //After open new tab, Nav Menue will close.
}
onClick={openTab}
If you'd like to set this globally for all users of a machine, you can create the following directory and file structures:
mkdir %windir%\Sun\Java\Deployment
Create a file deployment.config with the content:
deployment.system.config=file:///c:/windows/Sun/Java/Deployment/deployment.properties
deployment.system.config.mandatory=TRUE
Create a file deployment.properties
deployment.user.security.exception.sites=C\:/WINDOWS/Sun/Java/Deployment/exception.sites
Create a file exception.sites
http://example1.com
http://example2.com/path/to/specific/directory/
Reference https://blogs.oracle.com/java-platform-group/entry/upcoming_exception_site_list_in
Change visible="false"
to style="visibility:hidden"
on your tags..
or better use a class to show/hide the labels..
.hidden{
visibility:hidden;
}
then on your labels add class="hidden"
and with your script remove the class
document.getElementById("endTimeLabel").className = 'hidden'; // to hide
and
document.getElementById("endTimeLabel").className = ''; // to show
I'd just add to the answers the "why?".
.
is standard member access operator that has a higher precedence than *
pointer operator.
When you are trying to access a struct's internals and you wrote it as *foo.bar
then the compiler would think to want a 'bar' element of 'foo' (which is an address in memory) and obviously that mere address does not have any members.
Thus you need to ask the compiler to first dereference whith (*foo)
and then access the member element: (*foo).bar
, which is a bit clumsy to write so the good folks have come up with a shorthand version: foo->bar
which is sort of member access by pointer operator.
Just make a rule for each case:
<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1) }">
Or use the ternary operator:
<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'">
math.fabs()
converts its argument to float if it can (if it can't, it throws an exception). It then takes the absolute value, and returns the result as a float.
In addition to floats, abs()
also works with integers and complex numbers. Its return type depends on the type of its argument.
In [7]: type(abs(-2))
Out[7]: int
In [8]: type(abs(-2.0))
Out[8]: float
In [9]: type(abs(3+4j))
Out[9]: float
In [10]: type(math.fabs(-2))
Out[10]: float
In [11]: type(math.fabs(-2.0))
Out[11]: float
In [12]: type(math.fabs(3+4j))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/npe/<ipython-input-12-8368761369da> in <module>()
----> 1 type(math.fabs(3+4j))
TypeError: can't convert complex to float
If you use the HTML structure I lay out in this question you can simply float your label and input to the left and adjust padding/margin until things are lined up.
And yes, you'll want to make your radio button have a class name for old IE. And to have all of them on the same line, according to the markup I linked to above, it would be like so:
fieldset {_x000D_
overflow: hidden_x000D_
}_x000D_
_x000D_
.some-class {_x000D_
float: left;_x000D_
clear: none;_x000D_
}_x000D_
_x000D_
label {_x000D_
float: left;_x000D_
clear: none;_x000D_
display: block;_x000D_
padding: 0px 1em 0px 8px;_x000D_
}_x000D_
_x000D_
input[type=radio],_x000D_
input.radio {_x000D_
float: left;_x000D_
clear: none;_x000D_
margin: 2px 0 0 2px;_x000D_
}
_x000D_
<fieldset>_x000D_
<div class="some-class">_x000D_
<input type="radio" class="radio" name="x" value="y" id="y" />_x000D_
<label for="y">Thing 1</label>_x000D_
<input type="radio" class="radio" name="x" value="z" id="z" />_x000D_
<label for="z">Thing 2</label>_x000D_
</div>_x000D_
</fieldset>
_x000D_
addition to the previous answer add file path directory for the write operation
fs.writeFile(path.join(__dirname,jsonPath), JSON.stringify(newFileData), function (err) {}
I will let you decide if it's the fastest or not.
using System;
namespace PrimeNumbers
{
public static class Program
{
static int primesCount = 0;
public static void Main()
{
DateTime startingTime = DateTime.Now;
RangePrime(1,1000000);
DateTime endingTime = DateTime.Now;
TimeSpan span = endingTime - startingTime;
Console.WriteLine("span = {0}", span.TotalSeconds);
}
public static void RangePrime(int start, int end)
{
for (int i = start; i != end+1; i++)
{
bool isPrime = IsPrime(i);
if(isPrime)
{
primesCount++;
Console.WriteLine("number = {0}", i);
}
}
Console.WriteLine("primes count = {0}",primesCount);
}
public static bool IsPrime(int ToCheck)
{
if (ToCheck == 2) return true;
if (ToCheck < 2) return false;
if (IsOdd(ToCheck))
{
for (int i = 3; i <= (ToCheck / 3); i += 2)
{
if (ToCheck % i == 0) return false;
}
return true;
}
else return false; // even numbers(excluding 2) are composite
}
public static bool IsOdd(int ToCheck)
{
return ((ToCheck % 2 != 0) ? true : false);
}
}
}
It takes approximately 82 seconds to find and print prime numbers within a range of 1 to 1,000,000, on my Core 2 Duo laptop with a 2.40 GHz processor. And it found 78,498 prime numbers.
<a title="Pending Employee Approvals" href="" ng-click="viewPendingApprovals(1)">
<i class="fa fa-user" aria-hidden="true"></i>
<span class="button_badge">{{pendingEmployeeApprovalCount}}</span>
</a>
and in the controller
$scope.viewPendingApprovals = function(type) {
if (window.location.hash.substring(window.location.hash.lastIndexOf('/') + 1, window.location.hash.length) == type) {
location.reload();
} else {
$state.go("home.pendingApproval", { id: sessionStorage.typeToLoad });
}
};
and in the route file
.state('home.pendingApproval', {
url: '/pendingApproval/:id',
templateUrl: 'app/components/approvals/pendingApprovalList.html',
controller: 'pendingApprovalListController'
})
So, If the id passed in the url is same as what is coming from the function called by clicking the anchor, then simply reload, else folow the requested route.
Please help me improve this answer, if this is helps. Any, suggestions are welcome.
Your controller method should be like this:
@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
Person person = personService.getCurrentlyAuthenticatedUser();
int id = 2323; // Currently passing static values for testing
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
return "note";
}
Use the id
in your code, call the controller method from your JSP as:
/{your mapping}/{your id}
UPDATE:
Change your jsp code to:
<c:forEach items="${listNotes}" var="notices" varStatus="status">
<tr>
<td>${notices.noticesid}</td>
<td>${notices.notetext}</td>
<td>${notices.notetag}</td>
<td>${notices.notecolor}</td>
<td>${notices.sectionid}</td>
<td>${notices.canvasid}</td>
<td>${notices.canvasnName}</td>
<td>${notices.personid}</td>
<td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
<td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
</tr>
</c:forEach>
I made code for imageview with pinch to zoom using zoomageview. so user can drag the image off the screen and zoom-In , zoom-out the image.
You can follow this link
to get the Step By Step
Code and also given Output Screenshot.
Your approach works without any modification.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
// Timestamp for 2011-10-06 03:35:05 GMT
calendar.setTime(new Date(1317872105000L));
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("GMT+13"));
// Prints 2011-10-06 16:35:05 GMT+13:00
System.out.println(formatter.format(calendar.getTime()));
for people still not able to solve it, this answer helped me. stackoverflow answer: 34558264
TLDR;
one needs to set {withCredentials: true}
in both GET request as well the POST request (getting the cookie) for both axios as well as fetch.
This is a fairly straightforward way to do this, but it may not be the fastest. It is quite powerful because it is composable.
public static IEnumerable<int> ToBase(this int x, int b)
{
IEnumerable<int> ToBaseReverse()
{
if (x == 0)
{
yield return 0;
yield break;
}
int z = x;
while (z > 0)
{
yield return z % b;
z = z / b;
}
}
return ToBaseReverse().Reverse();
}
Combine this with this simple extension method and any getting any base is now possible:
public static string ToBase(this int number, string digits) =>
String.Concat(number.ToBase(digits.Length).Select(x => digits[x]));
It can be used like this:
var result = 23.ToBase("01");
var result2 = 23.ToBase("012X");
Console.WriteLine(result);
Console.WriteLine(result2);
The output is:
10111 11X
@echo off
color 1F
@sc query >%COMPUTERNAME%_START.TXT
find /I "AcPrfMgrSvc" %COMPUTERNAME%_START.TXT >nul
IF ERRORLEVEL 0 EXIT
IF ERRORLEVEL 1 NET START "AcPrfMgrSvc"
<div id="OK1" runat="server" style ="display:none" >
<asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
</div>
vb.net code
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex = 0 Then
OK1.Style.Add("display", "none")
Else
OK1.Style.Add("display", "block")
End If
End Sub
I know this is a very old question but it still doesn't have an accepted answer. I see that you want the following removed: html tags that are "empty" and white spaces based on an html string.
I have come up with a solution based on your comment for the output you are looking for:
Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces
var str = "<p> </p><div> </div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p> </p><div> </div>";_x000D_
console.log(str.trim().replace(/ /g, '').replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));
_x000D_
.trim()
removes leading and trailing whitespace
.replace(/ /g, '')
removes
.replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));
removes empty tags
Try just:
powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"
It should be clear by now that JavaScript offers no such solution natively; here are the closest two derivatives, the most useful first:
Array.prototype.some(fn)
offers the desired behaviour of stopping when a condition is met, but returns only whether an element is present; it's not hard to apply some trickery, such as the solution offered by Bergi's answer.
Array.prototype.filter(fn)[0]
makes for a great one-liner but is the least efficient, because you throw away N - 1
elements just to get what you need.
Traditional search methods in JavaScript are characterized by returning the index of the found element instead of the element itself or -1. This avoids having to choose a return value from the domain of all possible types; an index can only be a number and negative values are invalid.
Both solutions above don't support offset searching either, so I've decided to write this:
(function(ns) {
ns.search = function(array, callback, offset) {
var size = array.length;
offset = offset || 0;
if (offset >= size || offset <= -size) {
return -1;
} else if (offset < 0) {
offset = size - offset;
}
while (offset < size) {
if (callback(array[offset], offset, array)) {
return offset;
}
++offset;
}
return -1;
};
}(this));
search([1, 2, NaN, 4], Number.isNaN); // 2
search([1, 2, 3, 4], Number.isNaN); // -1
search([1, NaN, 3, NaN], Number.isNaN, 2); // 3
in controller just convert json data to object using json_decode php function like this
$member = json_decode($json_string);
and pass to view in view
return view('page',compact('$member'))
in view blade
Member ID: {{$member->member[0]->id}}
Firstname: {{$member->member[0]->firstname}}
Lastname: {{$member->member[0]->lastname}}
Phone: {{$member->member[0]->phone}}
Owner ID: {{$member->owner[0]->id}}
Firstname: {{$member->owner[0]->firstname}}
Lastname: {{$member->owner[0]->lastname}}
Here's a snippet of the HTML escape characters taken from a cached page on archive.org:
< | < less than sign
@ | @ at sign
] | ] right bracket
{ | { left curly brace
} | } right curly brace
… | … ellipsis
‡ | ‡ double dagger
’ | ’ right single quote
” | ” right double quote
– | – short dash
™ | ™ trademark
¢ | ¢ cent sign
¥ | ¥ yen sign
© | © copyright sign
¬ | ¬ logical not sign
° | ° degree sign
² | ² superscript 2
¹ | ¹ superscript 1
¼ | ¼ fraction 1/4
¾ | ¾ fraction 3/4
÷ | ÷ division sign
” | ” right double quote
> | > greater than sign
[ | [ left bracket
` | ` back apostrophe
| | | vertical bar
~ | ~ tilde
† | † dagger
‘ | ‘ left single quote
“ | “ left double quote
• | • bullet
— | — longer dash
¡ | ¡ inverted exclamation point
£ | £ pound sign
¦ | ¦ broken vertical bar
« | « double left than sign
® | ® registered trademark sign
± | ± plus or minus sign
³ | ³ superscript 3
» | » double greater-than sign
½ | ½ fraction 1/2
¿ | ¿ inverted question mark
“ | “ left double quote
— | — dash
If you really need to do this, use reverse proxy.
For example, with nginx as reverse proxy
server {
listen api.mydomain.com:80;
server_name api.mydomain.com;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
You can use Array.prototype.reduce() and actual JavaScript Map instead just a JavaScript Object.
let keyValueObjArray = [
{ key: 'key1', val: 'val1' },
{ key: 'key2', val: 'val2' },
{ key: 'key3', val: 'val3' }
];
let keyValueMap = keyValueObjArray.reduce((mapAccumulator, obj) => {
// either one of the following syntax works
// mapAccumulator[obj.key] = obj.val;
mapAccumulator.set(obj.key, obj.val);
return mapAccumulator;
}, new Map());
console.log(keyValueMap);
console.log(keyValueMap.size);
What is different between Map And Object?
Previously, before Map was implemented in JavaScript, Object has been used as a Map because of their similar structure.
Depending on your use case, if u need to need to have ordered keys, need to access the size of the map or have frequent addition and removal from the map, a Map is preferable.
Quote from MDN document:
Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this (and because there were no built-in alternatives), Objects have been used as Maps historically; however, there are important differences that make using a Map preferable in certain cases:
After reading around alot, only this worked: In class to set Shared preferences:
SharedPreferences userDetails = getApplicationContext().getSharedPreferences("test", MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.clear();
edit.putString("test1", "1");
edit.putString("test2", "2");
edit.commit();
In AlarmReciever:
SharedPreferences userDetails = context.getSharedPreferences("test", Context.MODE_PRIVATE);
String test1 = userDetails.getString("test1", "");
String test2 = userDetails.getString("test2", "");
Though already lots of answer is here. I came up with 3 solutions which I applied step by step when I faced this situation.
First step: From Official manual,
If you've previously installed create-react-app globally via
npm install -g create-react-app
, we recommend you uninstall the package usingnpm uninstall -g create-react-app
to ensure that npx always uses the latest version.
https://create-react-app.dev/docs/getting-started
You can use these commands below:
npx create-react-app my-app
npm init react-app my-app
yarn create react-app my-app
Second step (If first one doesn't work):
Sometimes it may keep caches.then you can use these commands given below.
npm uninstall -g create-react-app
npm cache clean --force
npm cache verify
yarn create react-app my-app
Third step:(If these 2 won't work)
first uninstall via npm uninstall -g create-react-app
,then check if you still have it "installed" with which create-react-app
command on your command line. If you got something like (/usr/local/bin/create-react-app) then run this rm -rf /usr/local/bin/create-react-app
(folder may vary) to delete manually.
Then again install it via npx/npm/yarn.
NB: I succeed in the last step.
Here's a different approach using CSS instead of JavaScript/AngularJS.
CSS:
.emptymsg {
display: list-item;
}
li + .emptymsg {
display: none;
}
Markup:
<ul>
<li ng-repeat="item in filteredItems"> ... </li>
<li class="emptymsg">No items found</li>
</ul>
If the list is empty, <li ng-repeat="item in filteredItems">, etc. will get commented out and will become a comment instead of a li element.
From official reference
Full-text indexes can be used only with MyISAM tables. (In MySQL 5.6 and up, they can also be used with InnoDB tables.) Full-text indexes can be created only for CHAR, VARCHAR, or TEXT columns.
https://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html
InnoDB with MySQL 5.5 does not support Full-text indexes.
var attr, object_information='';
for(attr in object){
//Get names and values of propertys with style (name : value)
object_information += attr + ' : ' + object[attr] + '\n';
}
alert(object_information); //Show all Object
Here's a way to convert binary numbers to ASCII characters that is often simple enough to do in your head.
1 - Convert every 4 binary digits into one hex digit.
Here's a binary to hex conversion chart:
0001 = 1
0010 = 2
0011 = 3
0100 = 4
0101 = 5
0110 = 6
0111 = 7
1000 = 8
1001 = 9
1010 = a (the hex number a, not the letter a)
1011 = b
1100 = c
1101 = d
1110 = e
1111 = f
(The hexadecimal numbers a through f are the decimal numbers 10 through 15. That's what hexadecimal, or "base 16" is - instead of each digit being capable of representing 10 different numbers [0 - 9], like decimal or "base 10" does, each digit is instead capable of representing 16 different numbers [0 - f].)
Once you know that chart, converting any string of binary digits into a string of hex digits is simple.
For example,
01000100 = 0100 0100 = 44 hex
1010001001110011 = 1010 0010 0111 0011 = a273 hex
Simple enough, right? It is a simple matter to convert a binary number of any length into its hexadecimal equivalent.
(This works because hexadecimal is base 16 and binary is base 2 and 16 is the 4th power of 2, so it takes 4 binary digits to make 1 hex digit. 10, on the other hand, is not a power of 2, so we can't convert binary to decimal nearly as easily.)
2 - Split the string of hex digits into pairs.
When converting a number into ASCII, every 2 hex digits is a character. So break the hex string into sets of 2 digits.
You would split a hex number like 7340298b392 this into 6 pairs, like this:
7340298b392 = 07 34 02 98 b3 92
(Notice I prepended a 0, since I had an odd number of hex digits.)
That's 6 pairs of hex digits, so its going to be 6 letters. (Except I know right away that 98, b3 and 92 aren't letters. I'll explain why in a minute.)
3 - Convert each pair of hex digits into a decimal number.
Do this by multiplying the (decimal equivalent of the) left digit by 16, and adding the 2nd.
For example, b3 hex = 11*16 + 3, which is 110 + 66 + 3, which is 179. (b hex is 11 decimal.)
4 - Convert the decimal numbers into ASCII characters.
Now, to get the ASCII letters for the decimal numbers, simply keep in mind that in ASCII, 65 is an uppercase 'A', and 97 is a lowercase 'a'.
So what letter is 68?
68 is the 4th letter of the alphabet in uppercase, right?
65 = A, 66 = B, 67 = C, 68 = D.
So 68 is 'D'.
You take the decimal number, subtract 64 for uppercase letters if the number is less than 97, or 96 for lowercase letters if the number is 97 or larger, and that's the number of the letter of the alphabet associated with that set of 2 hex digits.
Alternatively, if you're not afraid of a little bit of easy hex arithmetic, you can skip step 3, and just go straight from hex to ASCII, by remembering, for example, that
hex 41 = 'A'
hex 61 = 'a'
So subtract 40 hex for uppercase letters or 60 hex for lowercase letters, and convert what's left to decimal to get the alphabet letter number.
For example
01101100 = 6c, 6c - 60 = c = 12 decimal = 'l'
01010010 = 52, 52 - 40 = 12 hex = 18 decimal = 'R'
(When doing this, it's helpful to remember that 'm' (or 'M') is the 13 letter of the alphabet. So you can count up or down from 13 to find a letter that's nearer to the middle than to either end.)
I saw this on a shirt once, and was able to read it in my head:
01000100
01000001
01000100
I did it like this:
01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D
01000001 = 0100 0001 = 41 hex, - 40 hex = ucase letter 1 = A
01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D
The shirt said "DAD", which I thought was kinda cool, since it was being purchased by a pregnant woman. Her husband must be a geek like me.
How did I know right away that 92, b3, and 98 were not letters?
Because the ASCII code for a lowercase 'z' is 96 + 26 = 122, which in hex is 7a. 7a is the largest hex number for a letter. Anything larger than 7a is not a letter.
So that's how you can do it as a human.
How do computer programs do it?
For each set of 8 binary digits, convert it to a number, and look it up in an ASCII table.
(That's one pretty obvious and straight forward way. A typical programmer could probably think of 10 or 15 other ways in the space of a few minutes. The details depend on the computer language environment.)
The javaw command is identical to java, except that javaw has no associated console window. Use javaw when you do not want a command prompt window to be displayed. The javaw launcher displays a window with error information if it fails.
And javaws is for Java web start applications, applets, or something like that, I would suspect.
You have to do it inline. But you really don't need that swap in Java.
I made another variant with dropdown menu (perhaps for advanced search etc).. Here is how it looks like:
<div class="input-group my-4 col-6 mx-auto">
<input class="form-control py-2 border-right-0 border" type="search" placeholder="Type something..." id="example-search-input">
<span class="input-group-append">
<button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split border border-left-0 border-right-0 rounded-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<button class="btn btn-outline-primary rounded-right" type="button">
<i class="fas fa-search"></i>
</button>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
<div role="separator" class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Separated link</a>
</div>
</span>
</div>
Note: It appears green in the screenshot because my site main theme is green.
I enclosed C++ code for grabbing frames. It requires OpenCV version 2.0 or higher. The code uses cv::mat structure which is preferred to old IplImage structure.
#include "cv.h"
#include "highgui.h"
#include <iostream>
int main(int, char**) {
cv::VideoCapture vcap;
cv::Mat image;
const std::string videoStreamAddress = "rtsp://cam_address:554/live.sdp";
/* it may be an address of an mjpeg stream,
e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */
//open the video stream and make sure it's opened
if(!vcap.open(videoStreamAddress)) {
std::cout << "Error opening video stream or file" << std::endl;
return -1;
}
//Create output window for displaying frames.
//It's important to create this window outside of the `for` loop
//Otherwise this window will be created automatically each time you call
//`imshow(...)`, which is very inefficient.
cv::namedWindow("Output Window");
for(;;) {
if(!vcap.read(image)) {
std::cout << "No frame" << std::endl;
cv::waitKey();
}
cv::imshow("Output Window", image);
if(cv::waitKey(1) >= 0) break;
}
}
Update You can grab frames from H.264 RTSP streams. Look up your camera API for details to get the URL command. For example, for an Axis network camera the URL address might be:
// H.264 stream RTSP address, where 10.10.10.10 is an IP address
// and 554 is the port number
rtsp://10.10.10.10:554/axis-media/media.amp
// if the camera is password protected
rtsp://username:[email protected]:554/axis-media/media.amp
Here it is some code:
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();
See more examples in this article, you may need to take a look to impersonation.
For the automatic positioning of a single legend in a figure
with many axes, like those obtained with subplots()
, the following solution works really well:
plt.legend( lines, labels, loc = 'lower center', bbox_to_anchor = (0,-0.1,1,1),
bbox_transform = plt.gcf().transFigure )
With bbox_to_anchor
and bbox_transform=plt.gcf().transFigure
you are defining a new bounding box of the size of your figure
to be a reference for loc
. Using (0,-0.1,1,1)
moves this bouding box slightly downwards to prevent the legend to be placed over other artists.
OBS: use this solution AFTER you use fig.set_size_inches()
and BEFORE you use fig.tight_layout()
You can use ESCAPE
:
WHERE columnName LIKE '%\%%' ESCAPE '\'
I found solution here: https://code.visualstudio.com/docs/customization/colorizer
Go to VS_CODE_FOLDER/resources/app/extensions/
and there update package.json
You can maybe do something like this with awk
awk '{outfile=sprintf("file%02d.txt",NR/5000+1);print > outfile}' yourfile
Basically, it calculates the name of the output file by taking the record number (NR) and dividing it by 5000, adding 1, taking the integer of that and zero-padding to 2 places.
By default, awk
prints the entire input record when you don't specify anything else. So, print > outfile
writes the entire input record to the output file.
As you are running on Windows, you can't use single quotes because it doesn't like that. I think you have to put the script in a file and then tell awk
to use the file, something like this:
awk -f script.awk yourfile
and script.awk
will contain the script like this:
{outfile=sprintf("file%02d.txt",NR/5000+1);print > outfile}
Or, it may work if you do this:
awk "{outfile=sprintf(\"file%02d.txt\",NR/5000+1);print > outfile}" yourfile
Answer provided by Nicholas Krasnov
SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';
Compilr seems to be going in that direction: http://compilr.com/teachers
Use a view model that contains multiple view models:
namespace MyProject.Web.ViewModels
{
public class UserViewModel
{
public UserDto User { get; set; }
public ProductDto Product { get; set; }
public AddressDto Address { get; set; }
}
}
In your view:
@model MyProject.Web.ViewModels.UserViewModel
@Html.LabelFor(model => model.User.UserName)
@Html.LabelFor(model => model.Product.ProductName)
@Html.LabelFor(model => model.Address.StreetName)
Here is the explanation:
https://www.w3.org/TR/css-flexbox-1/#flex-common
flex: <positive-number>
Equivalent to flex: <positive-number> 1 0. Makes the flex item flexible and sets the flex basis to zero, resulting in an item that receives the specified proportion of the free space in the flex container. If all items in the flex container use this pattern, their sizes will be proportional to the specified flex factor.
Therefore flex:1
is equivalent to flex: 1 1 0
Possible Permission Issue
I know this post is fairly old, but I ran into a similar issue and my file was spelled correctly.
I originally created the app_offline.htm file in another location and then moved it to the root of my application. Because of my setup I then had a permissions issue.
The website acted as if it was not there. Creating the file within the root directory instead of moving it, fixed my problem. (Or you could just fix the permission in properties->security)
Hope it helps someone.
You need to set it to C:\Sun\SDK\jdk
(Assuming that is where the JDK is installed - It is not the default) - Do not put the \bin in C:\Sun\SDK\jdk\bin
.
If your app only runs when you are logged in as the current user then put it in the user variables - If it needs to run for all users on your system then put it in System variables.
You might also need to add %JAVA_HOME%\bin
to the path also (Also it depends on whether you run it from just the user or from all users, including System)
Follow these steps to create CSR (Code Signing Identity):
On your Mac, go to the folder 'Applications' ? 'Utilities' and open 'Keychain Access.'
Go to 'Keychain Access' ? Certificate Assistant ? Request a Certificate from a Certificate Authority. ?
Fill out the information in the Certificate Information window as specified below and click "Continue."
• In the User Email Address field, enter the email address to identify with this certificate
• In the Common Name field, enter your name
• In the Request group, click the "Saved to disk" option
?
Save the file to your hard drive.
Use this CSR (.certSigningRequest) file to create project/application certificates and profiles, in Apple developer account.
I will give simple steps to add favicon :-)
logo.png
Change logo.png
to favicon.ico
Note : when you save it is
favicon.ico
make sure it's notfavicon.ico.png
It might take some time to update
change icon size in manifest.json if you can't wait
Cursor itself is an iterator (like WHILE). By saying iterator I mean a way to traverse the record set (aka a set of selected data rows) and do operations on it while traversing. Operations could be INSERT or DELETE for example. Hence you can use it for data retrieval for example. Cursor works with the rows of the result set sequentially - row by row. A cursor can be viewed as a pointer to one row in a set of rows and can only reference one row at a time, but can move to other rows of the result set as needed.
This link can has a clear explanation of its syntax and contains additional information plus examples.
Cursors can be used in Sprocs too. They are a shortcut that allow you to use one query to do a task instead of several queries. However, cursors recognize scope and are considered undefined out of the scope of the sproc and their operations execute within a single procedure. A stored procedure cannot open, fetch, or close a cursor that was not declared in the procedure.
String test = "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
I suggest you look into getting composer
. https://getcomposer.org
Composer makes getting third-party libraries a LOT easier and using a single autoloader for all of them. It also standardizes on where all your dependencies are located, along with some automatization capabilities.
Download https://getcomposer.org/composer.phar to C:\Inetpub\wwwroot\php
Delete your C:\Inetpub\wwwroot\php\PHPMailer\
directory.
Use composer.phar
to get the phpmailer package using the command line to execute
cd C:\Inetpub\wwwroot\php
php composer.phar require phpmailer/phpmailer
After it is finished it will create a C:\Inetpub\wwwroot\php\vendor
directory along with all of the phpmailer files and generate an autoloader.
Next in your main project configuration file you need to include the autoload file.
require_once 'C:\Inetpub\wwwroot\php\vendor\autoload.php';
The vendor\autoload.php
will include the information for you to use $mail = new \PHPMailer;
Additional information on the PHPMailer package can be found at https://packagist.org/packages/phpmailer/phpmailer
You have to enable access first: Configuring Manager Application Access
If you want dynamic email templates for your mail then save the email content in your database tables. This is what i saved as HTML code in database =
<p>Hello.. {{ first_name }} {{ last_name }}. <br> This is an <strong>important</strong> {{ message }}
<br> <b> By Admin.</b>
<p style='color:red'> Good Day </p>
In your views:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
def dynamic_email(request):
application_obj = AppDetails.objects.get(id=1)
subject = 'First Interview Call'
email = request.user.email
to_email = application_obj.email
message = application_obj.message
text_content = 'This is an important message.'
d = {'first_name': application_obj.first_name,'message':message}
htmly = FirstInterviewCall.objects.get(id=1).html_content #this is what i have saved previously in database which i have to send as Email template as mentioned above HTML code
open("partner/templates/first_interview.html", "w").close() # this is the path of my file partner is the app, Here i am clearing the file content. If file not found it will create one on given path.
text_file = open("partner/templates/first_interview.html", "w") # opening my file
text_file.write(htmly) #putting HTML content in file which i saved in DB
text_file.close() #file close
htmly = get_template('first_interview.html')
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, text_content, email, [to_email])
msg.attach_alternative(html_content, "text/html")
msg.send()
This will send the dynamic HTML template what you have save in Db.
First thing I wann ans to this imp question: "Why we require PATH To be set?"
Answer : You need to set PATH to compile Java source code, create JAVA CLASS FILES and allow Operating System to load classes at runtime.
Now you will understand why after setting "javac" you can manually compile by just saying "Class_name.java"
Modify the PATH of Windows Environmental Variable by appending the location till bin directory where all exe file(for eg. java,javac) are present.
Example : ;C:\Program Files\Java\jre7\bin.
You can use .deepEqual()
const { assert } = require('chai');
assert.deepEqual([0,0], [0,0]);
tightVNC 2.5.X and even pre 2.5 supports multi monitor. When you connect, you get a huge virtual monitor. However, this is also has disadvantages. UltaVNC (Tho when I tried it, was buggy in this area) allows you to connect to one huge virtual monitor or just to 1 screen at a time. (With a button to cycle through them) TightVNC also plan to support such a feature.. (When , no idea) This feature is important as if you have large multi monitors and connecting over a reasonably slow link.. The screen updates are just to slow.. Cutting down to one monitor to focus on is desirable.
I like tightVNC, but UltraVNC seems to have a few more features right now..
I have found tightVNC more solid. And that is why I have stuck with it.
I would try both. They both work well, but I imagine one would suite slightly more then the other.
Have a go with these code:
>>> import pyexcel as pe
>>> sheet = pe.Sheet(data)
>>> data=[[1, 2], [2, 3], [4, 5]]
>>> sheet
Sheet Name: pyexcel
+---+---+
| 1 | 2 |
+---+---+
| 2 | 3 |
+---+---+
| 4 | 5 |
+---+---+
>>> sheet.save_as("one.csv")
>>> b = [[126, 125, 123, 122, 123, 125, 128, 127, 128, 129, 130, 130, 128, 126, 124, 126, 126, 128, 129, 130, 130, 130, 130, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 134, 134, 134, 134, 134, 134, 134, 134, 133, 134, 135, 134, 133, 133, 134, 135, 136], [135, 135, 136, 137, 137, 136, 134, 135, 135, 135, 134, 134, 133, 133, 133, 134, 134, 134, 133, 133, 132, 132, 132, 135, 135, 133, 133, 133, 133, 135, 135, 131, 135, 136, 134, 133, 136, 137, 136, 133, 134, 135, 136, 136, 135, 134, 133, 133, 134, 135, 136, 136, 136, 135, 134, 135, 138, 138, 135, 135, 138, 138, 135, 139], [137, 135, 136, 138, 139, 137, 135, 142, 139, 137, 139, 138, 136, 137, 141, 138, 138, 139, 139, 139, 139, 138, 138, 138, 138, 137, 137, 137, 137, 138, 138, 136, 137, 137, 137, 137, 137, 137, 138, 148, 144, 140, 138, 137, 138, 138, 138, 137, 137, 137, 137, 137, 138, 139, 140, 141, 141, 141, 141, 141, 141, 141, 141, 141], [141, 141, 141, 141, 141, 141, 141, 139, 139, 139, 140, 140, 141, 141, 141, 140, 140, 140, 140, 140, 141, 142, 143, 138, 138, 138, 139, 139, 140, 140, 140, 141, 140, 139, 139, 141, 141, 140, 139, 145, 137, 137, 145, 145, 137, 137, 144, 141, 139, 146, 134, 145, 140, 149, 144, 145, 142, 140, 141, 144, 145, 142, 139, 140]]
>>> s2 = pe.Sheet(b)
>>> s2
Sheet Name: pyexcel
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 126 | 125 | 123 | 122 | 123 | 125 | 128 | 127 | 128 | 129 | 130 | 130 | 128 | 126 | 124 | 126 | 126 | 128 | 129 | 130 | 130 | 130 | 130 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 133 | 134 | 135 | 134 | 133 | 133 | 134 | 135 | 136 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 135 | 135 | 136 | 137 | 137 | 136 | 134 | 135 | 135 | 135 | 134 | 134 | 133 | 133 | 133 | 134 | 134 | 134 | 133 | 133 | 132 | 132 | 132 | 135 | 135 | 133 | 133 | 133 | 133 | 135 | 135 | 131 | 135 | 136 | 134 | 133 | 136 | 137 | 136 | 133 | 134 | 135 | 136 | 136 | 135 | 134 | 133 | 133 | 134 | 135 | 136 | 136 | 136 | 135 | 134 | 135 | 138 | 138 | 135 | 135 | 138 | 138 | 135 | 139 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 137 | 135 | 136 | 138 | 139 | 137 | 135 | 142 | 139 | 137 | 139 | 138 | 136 | 137 | 141 | 138 | 138 | 139 | 139 | 139 | 139 | 138 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 138 | 138 | 136 | 137 | 137 | 137 | 137 | 137 | 137 | 138 | 148 | 144 | 140 | 138 | 137 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 137 | 138 | 139 | 140 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 141 | 141 | 141 | 141 | 141 | 141 | 141 | 139 | 139 | 139 | 140 | 140 | 141 | 141 | 141 | 140 | 140 | 140 | 140 | 140 | 141 | 142 | 143 | 138 | 138 | 138 | 139 | 139 | 140 | 140 | 140 | 141 | 140 | 139 | 139 | 141 | 141 | 140 | 139 | 145 | 137 | 137 | 145 | 145 | 137 | 137 | 144 | 141 | 139 | 146 | 134 | 145 | 140 | 149 | 144 | 145 | 142 | 140 | 141 | 144 | 145 | 142 | 139 | 140 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
>>> s2[0,0]
126
>>> s2.save_as("two.csv")
Jerryf's answer is fine, except for one flaw.
The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.
(Like Totty.js pointed out.)
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/ png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
You could use something like the following code:
string numbers = "numbers you want to check";
Regex regex = new Regex("^[0-9]+$"));
if (regex.IsMatch(numbers))
{
//string value is a number
}
Android Studio 3.4 + OpenCV 4.1
Download the latest OpenCV zip file from here (current newest version is 4.1.0) and unzip it in your workspace or in another folder.
Create new Android Studio project normally. Click File->New->Import Module
, navigate to /path_to_unzipped_files/OpenCV-android-sdk/sdk/java
, set Module name as opencv
, click Next
and uncheck all options in the screen.
Enable Project
file view mode (default mode is Android
). In the opencv/build.gradle
file change apply plugin: 'com.android.application'
to apply plugin: 'com.android.library'
and replace application ID "org.opencv"
with
minSdkVersion 21
targetSdkVersion 28
(according the values in app/build.gradle
). Sync project with Gradle files.
Add this string to the dependencies block in the app/build.gradle
file
dependencies {
...
implementation project(path: ':opencv')
...
}
Select again Android
file view mode. Right click on app
module and goto New->Folder->JNI Folder
. Select change folder location and set src/main/jniLibs/
.
Select again Project
file view mode and copy all folders from /path_to_unzipped_files/OpenCV-android-sdk/sdk/native/libs
to app/src/main/jniLibs
.
Again in Android
file view mode right click on app
module and choose Link C++ Project with Gradle
. Select Build System ndk-build
and path to OpenCV.mk
file /path_to_unzipped_files/OpenCV-android-sdk/sdk/native/jni/OpenCV.mk
.
path_to_unzipped_files
must not contain any spaces, or you will get error!
To check OpenCV initialization add Toast message in MainActivity onCreate()
method:
Toast.makeText(MainActivity.this, String.valueOf(OpenCVLoader.initDebug()), Toast.LENGTH_LONG).show();
If initialization is successful you will see true
in Toast message else you will see false
.
SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).
The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).
Clean your project Remove the /obj folder (probably using publish and deploy? - there is a bug in it)
Swift 4 solution:
cell.imageView?.image = UIImage(named: "yourImageName")
If this really is a QA issue and you can't change the code. Setup a new server instance on the machine and setup the language as "British English"
To name a few we can use redux-react-session which is having good API for session management like, initSessionService
, refreshFromLocalStorage
, checkAuth
and many other. It also provide some advanced functionality like Immutable JS
.
Alternatively we can leverage react-web-session which provides options like callback
and timeout
.
Java 8 added a new API for working with dates and times. With Java 8 you can use
import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();
Instant.now()
returns an Instant that represents the current system time. With getEpochSecond()
you get the epoch seconds (unix time) from the Instant
.
From:
it could be:
.html()
In an HTML document, .html()
can be used to get the contents of any element.
.text()
Unlike the .html()
method, .text()
can be used in both XML and HTML documents. The result of the .text()
method is a string containing the combined text of all matched elements.
.val()
The .val()
method is primarily used to get the values of form elements such as input
, select
and textarea
. When called on an empty collection, it returns undefined
.
For anchors, you should use title instead. alt is not valid atribute of a. See http://w3schools.com/tags/tag_a.asp
Try creating new instance of customer every time e.g.
while (rs.next()) {
Customer customer = new Customer();
customer.setId(rs.getInt("id"));
customer.setName(rs.getString("name"));
customer.setAddress(rs.getString("address"));
customer.setPhone(rs.getString("phone"));
customer.setEmail(rs.getString("email"));
customer.setBountPoints(rs.getInt("bonuspoint"));
customer.setTotalsale(rs.getInt("totalsale"));
customers.add(customer);
}
Get rid of the values
keyword and the parens. You can see an example here.
This is basic INSERT syntax:
INSERT INTO "table_name" ("column1", "column2", ...)
VALUES ("value1", "value2", ...);
This is the INSERT SELECT syntax:
INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2";
It is the ternary operator, and it works like in C (the parenthesis are not required). It's an expression that works like:
if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this
However, in Ruby, if
is also an expression so: if a then b else c end
=== a ? b : c
, except for precedence issues. Both are expressions.
Examples:
puts (if 1 then 2 else 3 end) # => 2
puts 1 ? 2 : 3 # => 2
x = if 1 then 2 else 3 end
puts x # => 2
Note that in the first case parenthesis are required (otherwise Ruby is confused because it thinks it is puts if 1
with some extra junk after it), but they are not required in the last case as said issue does not arise.
You can use the "long-if" form for readability on multiple lines:
question = if question.size > 20 then
question.slice(0, 20) + "..."
else
question
end
I use
\pagenumbering{roman}
for everything in the frontmatter and then switch over to
\pagenumbering{arabic}
for the actual content. With pdftex, the page numbers come out right in the PDF file.
If you are using something like this.
Response.Write("Hello \r\n")
Response.Write("World \r\n")
and the output is
Hello\r\nWorld\r\n
Then you are basically looking for something like this
Response.Write("Hello <br/>")
Response.Write("World <br/>")
This will output
Hello
World
you can also just define "<br />" as constant and reuse it
eg.
Public Const HtmlNewLine as string ="<br />"
Response.Write("Hello " & HtmlNewLine)
Response.Write("World " & HtmlNewLine)
I've been using Typescript in my current angular project for about a year and a half and while there are a few issues with definitions every now and then the DefinitelyTyped project does an amazing job at keeping up with the latest versions of most popular libraries.
Having said that there is a definite learning curve when transitioning from vanilla JavaScript to TS and you should take into account the ability of you and your team to make that transition. Also if you are going to be using angular 1.x most of the examples you will find online will require you to translate them from JS to TS and overall there are not a lot of resources on using TS and angular 1.x together right now.
If you plan on using angular 2 there are a lot of examples using TS and I think the team will continue to provide most of the documentation in TS, but you certainly don't have to use TS to use angular 2.
ES6 does have some nice features and I personally plan on getting more familiar with it but I would not consider it a production-ready language at this point. Mainly due to a lack of support by current browsers. Of course, you can write your code in ES6 and use a transpiler to get it to ES5, which seems to be the popular thing to do right now.
Overall I think the answer would come down to what you and your team are comfortable learning. I personally think both TS and ES6 will have good support and long futures, I prefer TS though because you tend to get language features quicker and right now the tooling support (in my opinion) is a little better.
The only reason to have a return in a void function would be to exit early due to some conditional statement:
void foo(int y)
{
if(y == 0) return;
// do stuff with y
}
As unwind said: when the code ends, it ends. No need for an explicit return at the end.
I use this SFTP API called Zehon, it's great, so easy to use with a lot of sample code. Here is the site http://www.zehon.com
Based in @TMS answer, I like it because there's no need for subqueries but I think ommiting the 'OR'
part will be sufficient and much simpler to understand and read.
SELECT t1.*
FROM lms_attendance AS t1
LEFT JOIN lms_attendance AS t2
ON t1.user = t2.user
AND t1.time < t2.time
WHERE t2.user IS NULL
if you are not interested in rows with null times you can filter them in the WHERE
clause:
SELECT t1.*
FROM lms_attendance AS t1
LEFT JOIN lms_attendance AS t2
ON t1.user = t2.user
AND t1.time < t2.time
WHERE t2.user IS NULL and t1.time IS NOT NULL
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
How It Works: First, open a ?le by using the built-in open function and specifying the name of the ?le and the mode in which we want to open the ?le. The mode can be a read mode (’r’), write mode (’w’) or append mode (’a’). We can also specify whether we are reading, writing, or appending in text mode (’t’) or binary mode (’b’). There are actually many more modes available and help(open) will give you more details about them. By default, open() considers the ?le to be a ’t’ext ?le and opens it in ’r’ead mode. In our example, we ?rst open the ?le in write text mode and use the write method of the ?le object to write to the ?le and then we ?nally close the ?le.
The above example is from the book "A Byte of Python" by Swaroop C H. swaroopch.com
You can now use Modern ECMAScript syntax thanks to V8 Runtime.
You can use includes():
var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}
The best solution that works for me without any problems looks this way:
1. Add temporary rule with some comment:
comment=$(cat /proc/sys/kernel/random/uuid | sed 's/\-//g')
iptables -A ..... -m comment --comment "${comment}" -j REQUIRED_ACTION
2. When the rule added and you wish to remove it (or everything with this comment), do:
iptables-save | grep -v "${comment}" | iptables-restore
So, you'll 100% delete all rules that match the $comment and leave other lines untouched. This solution works for last 2 months with about 100 changes of rules per day - no issues.Hope, it helps
For AVR Microcontrollers I wrote the following function, including relevant comments to make it easy to understand:
/**
* hex2int
* take a hex string and convert it to a 32bit number (max 8 hex digits)
*/
uint32_t hex2int(char *hex) {
uint32_t val = 0;
while (*hex) {
// get current character then increment
char byte = *hex++;
// transform hex character to the 4bit equivalent number, using the ascii table indexes
if (byte >= '0' && byte <= '9') byte = byte - '0';
else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;
// shift 4 to make space for new digit, and add the 4 bits of the new digit
val = (val << 4) | (byte & 0xF);
}
return val;
}
Example:
char *z ="82ABC1EF";
uint32_t x = hex2int(z);
printf("Number is [%X]\n", x);
sort ip_addresses | uniq -c
This will print the count first, but other than that it should be exactly what you want.
NAudio wraps the WaveOutXXXX API. I haven't looked at the source, but if NAudio exposes the waveOutWrite() function in a way that doesn't automatically stop playback on each call, then you should be able to do what you really want, which is to start playing the audio stream before you've received all the data.
Using the waveOutWrite() function allows you to "read ahead" and dump smaller chunks of audio into the output queue - Windows will automatically play the chunks seamlessly. Your code would have to take the compressed audio stream and convert it to small chunks of WAV audio on the fly; this part would be really difficult - all the libraries and components I've ever seen do MP3-to-WAV conversion an entire file at a time. Probably your only realistic chance is to do this using WMA instead of MP3, because you can write simple C# wrappers around the multimedia SDK.
You should use partial views. I use the following approach:
Use a view model so you're not passing your domain models to your views:
public class EditPersonViewModel
{
public int Id { get; set; } // this is only used to retrieve record from Db
public string Name { get; set; }
public string Age { get; set; }
}
In your PersonController:
[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{
var viewModel = new EditPersonViewModel();
viewModel.Id = id;
return PartialView("_EditPersonPartial", viewModel);
}
[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
if (ModelState.IsValid)
{
var toUpdate = personRepo.Find(viewModel.Id);
toUpdate.Name = viewModel.Name;
toUpdate.Age = viewModel.Age;
personRepo.InsertOrUpdate(toUpdate);
personRepo.Save();
return View("Index");
}
}
Next create a partial view called _EditPersonPartial
. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.
@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "list-of-people"
}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
<div class="modal-body">
@Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
@Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
</div>
<div class="modal-footer">
<button class="btn btn-inverse" type="submit">Save</button>
</div>
}
Now somewhere in your application, say another partial _peoplePartial.cshtml etc:
<div>
@foreach(var person in Model.People)
{
<button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
}
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
<div id="edit-person-container"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.edit-person').click(function () {
var url = "/Person/EditPerson"; // the url to the controller
var id = $(this).attr('data-id'); // the id that's given to each button in the list
$.get(url + '/' + id, function (data) {
$('#edit-person-container').html(data);
$('#edit-person').modal('show');
});
});
});
</script>
In android, we can easily check whether GPS is enabled in device or not using LocationManager.
Here is a simple program to Check.
GPS Enabled or Not :- Add the below user permission line in AndroidManifest.xml to Access Location
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Your java class file should be
public class ExampleApp extends Activity {
/** Called when the activity is first created. */
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}
}
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
The output will looks like
I've managed to find a CSS workaround to preventing bouncing of the viewport. The key was to wrap the content in 3 divs with -webkit-touch-overflow:scroll applied to them. The final div should have a min-height of 101%. In addition, you should explicitly set fixed widths/heights on the body tag representing the size of your device. I've added a red background on the body to demonstrate that it is the content that is now bouncing and not the mobile safari viewport.
Source code below and here is a plunker (this has been tested on iOS7 GM too). http://embed.plnkr.co/NCOFoY/preview
If you intend to run this as a full-screen app on iPhone 5, modify the height to 1136px (when apple-mobile-web-app-status-bar-style is set to 'black-translucent' or 1096px when set to 'black'). 920x is the height of the viewport once the chrome of mobile safari has been taken into account).
<!doctype html>
<html>
<head>
<meta name="viewport" content="initial-scale=0.5,maximum-scale=0.5,minimum-scale=0.5,user-scalable=no" />
<style>
body { width: 640px; height: 920px; overflow: hidden; margin: 0; padding: 0; background: red; }
.no-bounce { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
.no-bounce > div { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
.no-bounce > div > div { width: 100%; min-height: 101%; font-size: 30px; }
p { display: block; height: 50px; }
</style>
</head>
<body>
<div class="no-bounce">
<div>
<div>
<h1>Some title</h1>
<p>item 1</p>
<p>item 2</p>
<p>item 3</p>
<p>item 4</p>
<p>item 5</p>
<p>item 6</p>
<p>item 7</p>
<p>item 8</p>
<p>item 9</p>
<p>item 10</p>
<p>item 11</p>
<p>item 12</p>
<p>item 13</p>
<p>item 14</p>
<p>item 15</p>
<p>item 16</p>
<p>item 17</p>
<p>item 18</p>
<p>item 19</p>
<p>item 20</p>
</div>
</div>
</div>
</body>
</html>
Don't forget to add System.Net.Http, specially if you receive this error:
Severity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'HttpClient' could not be found (are you missing a using directive or an assembly reference?) 1_default.aspx D:\Projetos\Testes\FacebookAPI\FB-CustomAudience\default.aspx.cs 56 Active
In this case you shoud:
A query's projection can only have one instance of a given name. As your WHERE clause shows, you have several tables with a column called ID. Because you are selecting *
your projection will have several columns called ID. Or it would have were it not for the compiler hurling ORA-00918.
The solution is quite simple: you will have to expand the projection to explicitly select named columns. Then you can either leave out the duplicate columns, retaining just (say) COACHES.ID or use column aliases: coaches.id as COACHES_ID
.
Perhaps that strikes you as a lot of typing, but it is the only way. If it is any comfort, SELECT *
is regarded as bad practice in production code: explicitly named columns are much safer.
mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8
Here's a really simple API that I created for reading simple XML files in Java. It's incredibly simple and easy to use. Hope it's useful for you.
OSError: [WinError 193] %1 is not a valid Win32 application
This error is most probably due to this line import subprocess
I had the same issue and had solved it by uninstalling and reinstalling python and anaconda then i used jupyter and wrote pip install numpy this gave me the whole path where it was getting my site-packages from i deleted my site-packages folder and then the error dissappeared. Actually because i had 2 folders for site-packages one with anaconda and other somewhere in app data(which had some issues in it), since i deleted that site-package folder then it automatically started taking my libraries from site-package folder which was with anaconda hence the problem was solved.
The difference between getHeight()
and getMeasuredHeight()
is that first method will return actual height of the View
, the second one will return summary height of View
's children. In ohter words, getHeight()
returns view height, getMeasuredHeight()
returns height which this view needs to show all it's elements
The simplest way to extract a number from a string is to use regular expressions and findall
.
>>> import re
>>> s = '300 gm'
>>> re.findall('\d+', s)
['300']
>>> s = '300 gm 200 kgm some more stuff a number: 439843'
>>> re.findall('\d+', s)
['300', '200', '439843']
It might be that you need something more complex, but this is a good first step.
Note that you'll still have to call int
on the result to get a proper numeric type (rather than another string):
>>> map(int, re.findall('\d+', s))
[300, 200, 439843]
I got the same error when I just copied the complete line but when I rewrite the code again i.e. instead of copy-paste, writing it completely then the error was no longer present.
Conclusion: There might be some unacceptable words to the language got copied giving rise to this error.
I would generally prefer something a bit simpler, like activate
/deactivate
sub-resource (linked by a Link
header with rel=service
).
POST /groups/api/v1/groups/{group id}/activate
or
POST /groups/api/v1/groups/{group id}/deactivate
For the consumer, this interface is dead-simple, and it follows REST principles without bogging you down in conceptualizing "activations" as individual resources.
In addition to the simple addition shown by others, you can also use seq.Date
or seq.POSIXt
to find other increments or decrements (the POSIXt version does seconds, minutes, hours, etc.):
> seq.Date( Sys.Date(), length=2, by='3 months' )[2]
[1] "2012-07-25"
you can round your double and cast ist:
(int)Math.Round(myDouble);
The BigInt
data type is supported since Node.js 10.7.0. (see also the blog post announcement). For these supported versions of Node.js, the process.hrtime([time])
method is now regarded as 'legacy', replaced by the process.hrtime.bigint()
method.
The
bigint
version of theprocess.hrtime()
method returning the current high-resolution real time in abigint
.
const start = process.hrtime.bigint();
// 191051479007711n
setTimeout(() => {
const end = process.hrtime.bigint();
// 191052633396993n
console.log(`Benchmark took ${end - start} nanoseconds`);
// Benchmark took 1154389282 nanoseconds
}, 1000);
tl;dr
process.hrtime.bigint()
process.hrtime()
Nothing could be simple than this. Use OkHttpLibrary
Create your json
JSONObject requestObject = new JSONObject();
requestObject.put("Email", email);
requestObject.put("Password", password);
and send it like this.
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.addHeader("Content-Type","application/json")
.url(url)
.post(requestObject.toString())
.build();
okhttp3.Response response = client.newCall(request).execute();
How to get all data from database to view using laravel, i hope this solution would be helpful for the beginners.
Inside your controller
public function get(){
$types = select::all();
return view('selectview')->with('types', $types);}
Import data model inside your controller, in my application the data model named as select.
use App\Select;
Inclusive of both my controller looks something like this
use App\Select;
class SelectController extends Controller{
public function get(){
$types = select::all();
return view('selectview')->with('types', $types);}
select model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Select extends Model
{
protected $fillable = [
'name', 'email','phone','radio1','service',
];
protected $table = 'selectdata';
public $timestamps = false;
}
inside router
Route::get('/selectview', 'SelectController@get');
selectview.blade.php
@foreach($types as $type)
<ul>
<li>{{ $type->name }}</li>
</ul>
@endforeach
A constructor is basically a method that you can use to ensure that objects of your class are born valid. This is the main motivation for a constructor.
Let's say you want your class has a single integer field that should be always larger than zero. How do you do that in a way that is reliable?
public class C {
private int number;
public C(int number) {
setNumber(number);
}
public void setNumber(int number) {
if (number < 1) {
throws IllegalArgumentException("C cannot store anything smaller than 1");
}
this.number = number;
}
}
In the code above, it may look like you are doing something redundant, but in fact you are ensuring that the number is always valid no matter what.
"initialize the instances of a class" is what a constructor does, but not the reason why we have constructors. The question is about the purpose of a constructor. You can also initialize instances of a class externally, using c.setNumber(10)
in the example above. So a constructor is not the only way to initialize instances.
The constructor does that but in a way that is safe. In other words, a class alone solves the whole problem of ensuring their objects are always in valid states. Not using a constructor will leave such validation to the outside world, which is bad design.
Here is another example:
public class Interval {
private long start;
private long end;
public Interval(long start, long end) {
changeInterval(start, end);
}
public void changeInterval(long start, long end) {
if (start >= end) {
throw new IllegalArgumentException("Invalid interval.");
}
this.start = start;
this.end = end;
}
public long duration() {
return end - start;
}
}
The Interval class represents a time interval. Time is stored using long. It does not make any sense to have an interval that ends before it starts. By using a constructor like the one above it is impossible to have an instance of Interval at any given moment anywhere in the system that stores an interval that does not make sense.
If you mean all columns whose email is unique:
SELECT * FROM table WHERE email in
(SELECT email FROM table GROUP BY email HAVING COUNT(email)=1);
java.lang.ClassNotFoundException is indicate that class is not found in class path. it could be the version of log4j is not compatible. check for different log4j version.
I wrote a plugin that can fire callbacks when images have loaded in elements, or fire once per image loaded.
It is similar to $(window).load(function() { .. })
, except it lets you define any selector to check. If you only want to know when all images in #content
(for example) have loaded, this is the plugin for you.
It also supports loading of images referenced in the CSS, such as background-image
, list-style-image
, etc.
$('selector').waitForImages(function() {
alert('All images are loaded.');
});
More documentation is available on the GitHub page.
Here are some easy way to get you up and running with the XlsxWriter module.The first step is to install the XlsxWriter module.The pip installer is the preferred method for installing Python modules from PyPI, the Python Package Index:
sudo pip install xlsxwriter
Note
Windows users can omit sudo at the start of the command.
You basically effectively converted your date in a string format to a date object. If you print it out at that point, you will get the standard date formatting output. In order to format it after that, you then need to convert it back to a date object with a specified format (already specified previously)
String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate;
try {
startDate = df.parse(startDateString);
String newDateString = df.format(startDate);
System.out.println(newDateString);
} catch (ParseException e) {
e.printStackTrace();
}
I had a very similar issue. I got the same error because the csv contained spaces in the header. My csv contained a header "Gender " and I had it listed as:
[['Gender']]
If it's easy enough for you to access your csv, you can use the excel formula trim()
to clip any spaces of the cells.
or remove it like this
df.columns = df.columns.to_series().apply(lambda x: x.strip())
This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.
wp_users
, add a key, like abc123 to the
user_activation
column. Simply cleaning the project solved it for me.
My project is a C++ application (not a shared library). I randomly got this error after a lot of successful builds.
Great way of implementing Camera session in Swift 5, iOS 13
https://github.com/egzonpllana/CameraSession
Camera Session is an iOS app that tries to make the simplest possible way of implementation of AVCaptureSession.
Through the app you can find these camera session implemented:
The custom camera features like torch and rotate camera options.
I want to extend this topic/answers with the following. As someone mentioned, this auto-generated AssemblyInfo can be an obstacle for the external tools. In my case, using FinalBuilder, I had an issue that AssemblyInfo wasn't getting updated by build action. Apparently, FinalBuilder relies on ~proj
file to find location of the AssemblyInfo. I thought, it was looking anywhere under project folder. No. So, changing this
<PropertyGroup>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
did only half the job, it allowed custom assembly info if built by VS IDE/MS Build. But I needed FinalBuilder do it too without manual manipulations to assembly info file. I needed to satisfy all programs, MSBuild/VS and FinalBuilder.
I solved this by adding an entry to the existing ItemGroup
<ItemGroup>
<Compile Remove="Common\**" />
<Content Remove="Common\**" />
<EmbeddedResource Remove="Common\**" />
<None Remove="Common\**" />
<!-- new added item -->
<None Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
Now, having this item, FinalBuilder finds location of AssemblyInfo and modifies the file. While action None
allows MSBuild/DevEnv ignore this entry and no longer report an error based on Compile
action that usually comes with Assembly Info entry in proj
files.
C:\Program Files\dotnet\sdk\2.0.2\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.DefaultItems.targets(263,5): error : Duplicate 'Compile' items were included. The .NET SDK includes 'Compile' items from your project directory by default. You can either remove these items from your project file, or set the 'EnableDefaultCompileItems' property to 'false' if you want to explicitly include them in your project file. For more information, see https://aka.ms/sdkimplicititems. The duplicate items were: 'AssemblyInfo.cs'
I have been looking for the same solution and this worked for me...add an inline css tag to control the width of the input.
For example:
<input type="number" min="1" max="5" style="width: 2em;">
Combined with the min and max attributes you can control the width of the input.
Although abs(x - y)
or equivalently abs(y - x)
is preferred, if you are curious about a different answer, the following one-liners also work:
max(x - y, y - x)
-min(x - y, y - x)
max(x, y) - min(x, y)
(x - y) * math.copysign(1, x - y)
, or equivalently (d := x - y) * math.copysign(1, d)
in Python =3.8
functools.reduce(operator.sub, sorted([x, y], reverse=True))
Add one more simple solution
$(function() {
$('.monthYearPicker').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'M yy'
}).focus(function() {
var thisCalendar = $(this);
$('.ui-datepicker-calendar').detach();
$('.ui-datepicker-close').click(function() {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
thisCalendar.datepicker('setDate', new Date(year, month, 1));
});
});
});
http://jsfiddle.net/tmnasim/JLydp/
Features:
CASE might help you out:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
WHEN status_flag = STATUS_INACTIVE THEN 'T'
ELSE null END)
AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
WHEN source_flag = SOURCE_USER THEN 'users'
ELSE null END)
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.
This way can be helpful if you want to comment some Django Template format Code.
{#% include 'file.html' %#}
(Right Way)
Following code still executes if commented with HTML Comment.
<!-- {% include 'file.html' %} -->
(Wrong Way)
There's no built-in way, you'll have to loop over all of them:
function setAll(a, v) {
var i, n = a.length;
for (i = 0; i < n; ++i) {
a[i] = v;
}
}
http://jsfiddle.net/alnitak/xG88A/
If you really want, do this:
Array.prototype.setAll = function(v) {
var i, n = this.length;
for (i = 0; i < n; ++i) {
this[i] = v;
}
};
and then you could actually do cool.setAll(42)
(see http://jsfiddle.net/alnitak/ee3hb/).
Some people frown upon extending the prototype of built-in types, though.
EDIT ES5 introduced a way to safely extend both Object.prototype
and Array.prototype
without breaking for ... in ...
enumeration:
Object.defineProperty(Array.prototype, 'setAll', {
value: function(v) {
...
}
});
EDIT 2 In ES6 draft there's also now Array.prototype.fill
, usage cool.fill(42)
shell_exec
- Execute command via shell and return the complete output as a string
exec
- Execute an external program.
The difference is that with shell_exec
you get output as a return value.
Mint 18.2 (Cinnamon)
Menu > Keyboard Preferences > Layouts > Options > Switching to another layout:
In this Question, best answer not work for me. After that i found this method to show listview footer,
LayoutInflater inflater = getLayoutInflater();
ViewGroup footerView = (ViewGroup)inflater.inflate(R.layout.footer_layout,listView,false);
listView.addFooterView(footerView, null, false);
And create new layout call footer_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Done"
android:textStyle="italic"
android:background="#d6cf55"
android:padding="10dp"/>
</LinearLayout>
If not work refer this article hear
The model (@Model
) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.
What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor
will suffice.
However, you will want to change your foreach loop to a for loop. The final solution will look something like this:
for (int i = 0 ; i < Model.Post; i++)
{
<br/>
<b>Posted by :</b> @Model.Post[i].Username <br/>
<span>@Model.Post[i].Content</span> <br/>
if(Model.loginuser == Model.username)
{
@Html.HiddenFor(model => model.Post[i].PostID)
@Html.TextAreaFor(model => model.addcomment.Content)
<button type="submit">Add Comment</button>
}
}
System.setProperty is not working for applets. Because JVM already running before applet start. In this case we use applet parameters like this:
deployJava.runApplet({
id: 'MyApplet',
code: 'com.mkysoft.myapplet.SomeClass',
archive: 'com.mkysoft.myapplet.jar'
}, {
java_version: "1.6*", // Target version
cache_option: "no",
cache_archive: "",
codebase_lookup: true,
java_arguments: "-Djava.net.preferIPv4Stack=true"
},
"1.6" // Minimum version
);
You can find deployJava.js at https://www.java.com/js/deployJava.js
The problem is that you're (probably) trying to plot a vector that consists exclusively of missing (NA
) values. Here's an example:
> x=rep(NA,100)
> y=rnorm(100)
> plot(x,y)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
In your example this means that in your line plot(costs,pseudor2,type="l")
, costs
is completely NA
. You have to figure out why this is, but that's the explanation of your error.
From comments:
Scott C Wilson: Another possible cause of this message (not in this case, but in others) is attempting to use character values as X or Y data. You can use the class function to check your x and Y values to be sure if you think this might be your issue.
stevec: Here is a quick and easy solution to that problem (basically wrap x in as.factor(x)
)
Take a look at rogerdudler/eclipse-ui-themes . In the readme there is a link to a file that you need to extract into your eclipse/dropins
folder.
When you have done that go to
Window -> Preferences -> General -> Appearance
And change the theme from GTK (or what ever it is currently) to Dark Juno
(or Dark).
That will change the UI to a nice dark theme but to get the complete look and feel you can get the Eclipse Color Theme plugin from eclipsecolorthemes.org. The easiest way is to add this update URI to "Help -> Install New Software" and install it from there.
This adds a "Color Theme" menu item under
Window -> Preferences -> Appearance
Where you can select from a large range of editor themes. My preferred one to use with PyDev is Wombat. For Java Solarized Dark
Microsoft API Code Pack. ShellObjectWatcher class.
I created a lightweight SMTP Email sender for PHP if anybody needs it here is the URL
https://github.com/jerryurenaa/EZMAIL
Tested in both environments production and development.
I hope it helps new folks looking for a simple solution.