The way your radios are set up in the fiddle - sharing the same model - will cause only the last group to show a checked radio if you decide to quote all of the truthy values. A more solid approach will involve giving the individual groups their own model, and set the value as a unique attribute of the radios, such as the id:
$scope.radioMod = 1;
$scope.radioMod2 = 2;
Here is a representation of the new html:
<label data-ng-repeat="choice2 in question2.choices">
<input type="radio" name="response2" data-ng-model="radioMod2" value="{{choice2.id}}"/>
{{choice2.text}}
</label>
For the first example and base on the django's doc
It will always return the second list, indeed a non empty list is see as a True value for Python thus python return the 'last' True value so the second list
In [74]: mylist1 = [False]
In [75]: mylist2 = [False, True, False, True, False]
In [76]: mylist1 and mylist2
Out[76]: [False, True, False, True, False]
In [77]: mylist2 and mylist1
Out[77]: [False]
I've looked at the Jenkins source and it appears that what I'm trying to do is impossible, because stopping a job appears to be done via a Thread interrupt. I have no idea why the job is hanging though..
Edit:
Possible reasons for unstoppable jobs:
The main issue is that you haven't supplied the first grep with any input. You will need to reorder your command something like
grep "word1" logs | grep "word2"
If you want to count the occurences, then put a '-c' on the second grep.
For Internet Explorer, there is another solution:
There's one big difference between CLOCK_REALTIME and MONOTONIC. CLOCK_REALTIME can jump forward or backward according to NTP. By default, NTP allows the clock rate to be speeded up or slowed down by up to 0.05%, but NTP cannot cause the monotonic clock to jump forward or backward.
The solution is quite simple ... you're reading getchar() which gives you the first character in the input buffer, and scanf just parsed it (really don't know why) to an integer, if you just forget the getchar for a second, it will read the full buffer until a newline char.
printf("> ");
int x;
scanf("%d", &x);
printf("got the number: %d", x);
> [prompt expecting input, lets write:] 1234 [Enter]
got the number: 1234
I checked off Google API as project build target.
That is irrelevant, as that is for Maps V1, and you are trying to use Maps V2.
I included .jar file for maps by right-clicking on my project, went to build path and added external archive locating it in my SDK: android-sdk-windows\add-ons\addon_google_apis_google_inc_8\libs\maps
This is doubly wrong.
First, never manually modify the build path in an Android project. If you are doing that, at best, you will crash at runtime, because the JAR you think you put in your project (via the manual build path change) is not in your APK. For an ordinary third-party JAR, put it in the libs/
directory of your project, which will add it to your build path automatically and add its contents to your APK file.
However, Maps V2 is not a JAR. It is an Android library project that contains a JAR. You need the whole library project.
You need to import the android-sdk-windows\add-ons\addon_google_apis_google_inc_8
project into Eclipse, then add it to your app as a reference to an Android library project.
For bootstrap 4 just add this class:
w-100
String can be as large as 2GB.
Source
Came across this issue after I merged a pull request on Bitbucket.
Had to do
git fetch
and that was it.
If you are like me just want to print a sequence within a lambda, without get the return value (list of None).
x = range(3)
from __future__ import print_function # if not python 3
pra = lambda seq=x: map(print,seq) and None # pra for 'print all'
pra()
pra('abc')
I think you've created your project like this:
vue init webpack myproject
Well, now you can run
npm run build
Copy index.html and /dist/ folder into your website root directory. Done.
import difflib
f=open('a.txt','r') #open a file
f1=open('b.txt','r') #open another file to compare
str1=f.read()
str2=f1.read()
str1=str1.split() #split the words in file by default through the spce
str2=str2.split()
d=difflib.Differ() # compare and just print
diff=list(d.compare(str2,str1))
print '\n'.join(diff)
LinkedList<String>list = new LinkedList<String>();
list.add("abc");
list.add("Bcd");
list.add("aAb");
list.sort(String::compareToIgnoreCase);
Another option would be using lambda expressions:
list.sort((o1, o2) -> o1.compareToIgnoreCase(o2));
You get the cursor position by calling GetCursorPos
.
POINT p;
if (GetCursorPos(&p))
{
//cursor position now in p.x and p.y
}
This returns the cursor position relative to screen coordinates. Call ScreenToClient
to map to window coordinates.
if (ScreenToClient(hwnd, &p))
{
//p.x and p.y are now relative to hwnd's client area
}
You hide and show the cursor with ShowCursor
.
ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again
You must ensure that every call to hide the cursor is matched by one that shows it again.
Here you have another solution based on the one provided by @tarheel
function onEdit() {
var sheetWithNestedSelectsName = "Sitemap";
var columnWithNestedSelectsRoot = 1;
var sheetWithOptionPossibleValuesSuffix = "TabSections";
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = SpreadsheetApp.getActiveSheet();
// If we're not in the sheet with nested selects, exit!
if ( activeSheet.getName() != sheetWithNestedSelectsName ) {
return;
}
var activeCell = SpreadsheetApp.getActiveRange();
// If we're not in the root column or a content row, exit!
if ( activeCell.getColumn() != columnWithNestedSelectsRoot || activeCell.getRow() < 2 ) {
return;
}
var sheetWithActiveOptionPossibleValues = activeSpreadsheet.getSheetByName( activeCell.getValue() + sheetWithOptionPossibleValuesSuffix );
// Get all possible values
var activeOptionPossibleValues = sheetWithActiveOptionPossibleValues.getSheetValues( 1, 1, -1, 1 );
var possibleValuesValidation = SpreadsheetApp.newDataValidation();
possibleValuesValidation.setAllowInvalid( false );
possibleValuesValidation.requireValueInList( activeOptionPossibleValues, true );
activeSheet.getRange( activeCell.getRow(), activeCell.getColumn() + 1 ).setDataValidation( possibleValuesValidation.build() );
}
It has some benefits over the other approach:
So, how to use it:
Enjoy!
One advantage (albeit very slight) of defining string constants is that you can concatenate them at compile time:
#define HELLO "hello"
#define WORLD "world"
puts( HELLO WORLD );
Not sure that's really an advantage, but it is a technique that cannot be used with const char *
's.
Message queues are ideal for requests which may take a long time to process. Requests are queued and can be processed offline without blocking the client. If the client needs to be notified of completion, you can provide a way for the client to periodically check the status of the request.
Message queues also allow you to scale better across time. It improves your ability to handle bursts of heavy activity, because the actual processing can be distributed across time.
Note that message queues and web services are orthogonal concepts, i.e. they are not mutually exclusive. E.g. you can have a XML based web service which acts as an interface to a message queue. I think the distinction your looking for is Message Queues versus Request/Response, the latter is when the request is processed synchronously.
ISO standard C++ doesn't let you do this. If it did, the syntax would probably be:
a::a(void) :
b({2,3})
{
// other initialization stuff
}
Or something along those lines. From your question it actually sounds like what you want is a constant class (aka static) member that is the array. C++ does let you do this. Like so:
#include <iostream>
class A
{
public:
A();
static const int a[2];
};
const int A::a[2] = {0, 1};
A::A()
{
}
int main (int argc, char * const argv[])
{
std::cout << "A::a => " << A::a[0] << ", " << A::a[1] << "\n";
return 0;
}
The output being:
A::a => 0, 1
Now of course since this is a static class member it is the same for every instance of class A. If that is not what you want, ie you want each instance of A to have different element values in the array a then you're making the mistake of trying to make the array const to begin with. You should just be doing this:
#include <iostream>
class A
{
public:
A();
int a[2];
};
A::A()
{
a[0] = 9; // or some calculation
a[1] = 10; // or some calculation
}
int main (int argc, char * const argv[])
{
A v;
std::cout << "v.a => " << v.a[0] << ", " << v.a[1] << "\n";
return 0;
}
I have experienced that it is not safe (VS2010) to delete[] NULL (i.e. array syntax). I'm not sure whether this is according to the C++ standard.
It is safe to delete NULL (scalar syntax).
as @JAC pointed out in the comments of the highest rated answer, the generic solution (for all numpy types) can be found in the thread Converting numpy dtypes to native python types.
Nevertheless, I´ll add my version of the solution below, as my in my case I needed a generic solution that combines these answers and with the answers of the other thread. This should work with almost all numpy types.
def convert(o):
if isinstance(o, np.generic): return o.item()
raise TypeError
json.dumps({'value': numpy.int64(42)}, default=convert)
For .NET development, VS2008 is the best but if you want to check for another best IDE, Eclipse probably the best after VS if you are rating it among the IDEs, ofcourse you cant do .NET development in Eclipse though
You have writer.close();
in your code. So bash receives EOF on its stdin
and exits. Then you get Broken pipe
when trying to read from the stdout
of the defunct bash.
This is just about the most bizarre query I've ever written, but I'm pretty sure it gets the "last 5" rows from a table without ordering:
select *
from issues
where issueid not in (
select top (
(select count(*) from issues) - 5
) issueid
from issues
)
Note that this makes use of SQL Server 2005's ability to pass a value into the "top" clause - it doesn't work on SQL Server 2000.
Put this .gitignore
into the folder, then git add .gitignore
.
*
*/
!.gitignore
The *
line tells git to ignore all files in the folder, but !.gitignore
tells git to still include the .gitignore
file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore
it needs.
Edit: May be obvious but also add */
to the .gitignore
to also ignore subfolders.
SQLDeveloper can do this.
Most of the times when I face this issue. I remove replace https
with http
. It solves the issue.
It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.
Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.
DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj
...
The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.
var DyObjectsList = new List<dynamic>;
if (condition1) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = true;
DyObj.Message = "Message 1";
DyObjectsList .Add(DyObj);
}
if (condition2) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = false;
DyObj.Message = "Message 2";
DyObjectsList .Add(DyObj);
}
your resulting List essentially looks like this
DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj
Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.
However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.
Example call
String str = getStringFromUrl("YourUrl");
Implementation
You can use the method described in this answer, on How to read URL to an InputStream and combine it with this answer on How to read InputStream to String.
The outcome will be something like
public String getStringFromUrl(URL url) throws IOException {
return inputStreamToString(urlToInputStream(url,null));
}
public String inputStreamToString(InputStream inputStream) throws IOException {
try(ByteArrayOutputStream result = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString(UTF_8);
}
}
private InputStream urlToInputStream(URL url, Map<String, String> args) {
HttpURLConnection con = null;
InputStream inputStream = null;
try {
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(15000);
con.setReadTimeout(15000);
if (args != null) {
for (Entry<String, String> e : args.entrySet()) {
con.setRequestProperty(e.getKey(), e.getValue());
}
}
con.connect();
int responseCode = con.getResponseCode();
/* By default the connection will follow redirects. The following
* block is only entered if the implementation of HttpURLConnection
* does not perform the redirect. The exact behavior depends to
* the actual implementation (e.g. sun.net).
* !!! Attention: This block allows the connection to
* switch protocols (e.g. HTTP to HTTPS), which is <b>not</b>
* default behavior. See: https://stackoverflow.com/questions/1884230
* for more info!!!
*/
if (responseCode < 400 && responseCode > 299) {
String redirectUrl = con.getHeaderField("Location");
try {
URL newUrl = new URL(redirectUrl);
return urlToInputStream(newUrl, args);
} catch (MalformedURLException e) {
URL newUrl = new URL(url.getProtocol() + "://" + url.getHost() + redirectUrl);
return urlToInputStream(newUrl, args);
}
}
/*!!!!!*/
inputStream = con.getInputStream();
return inputStream;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Pros
It is pure java
It can be easily enhanced by adding different headers (instead of passing a null object, like the example above does), authentication, etc.
Handling of protocol switches is supported
You just need to manually set the desired permissions with chmod()
:
private function writeFileContent($file, $content){
$fp = fopen($file, 'w');
fwrite($fp, $content);
fclose($fp);
// Set perms with chmod()
chmod($file, 0777);
return true;
}
You can try this:
const data = {
name : "Test",
value: 12
}
if("name" in data){
//Found
}
else {
//Not found
}
Alternative way (but it's not python style. It's JS style)
{{ files and 'Update' or 'Continue' }}
This is not an answer, really and I would have entered it as a comment had the question not been locked. This answers the question:
Why would you want it?
Assume you have a table with the sequence as the primary key and the sequence is generated by an insert trigger. If you wanted to have the sequence available for subsequent updates to the record, you need to have a way to extract that value.
In order to make sure you get the right one, you might want to wrap the INSERT and RonK's query in a transaction.
RonK's Query:
select MY_SEQ_NAME.currval from DUAL;
In the above scenario, RonK's caveat does not apply since the insert and update would happen in the same session.
If you have a LDAP connection with a username and password to connect to Active Directory, here is the code I used to connect properly:
using System.DirectoryServices.AccountManagement;
// ...
// Connection information
var connectionString = "LDAP://domain.com/DC=domain,DC=com";
var connectionUsername = "your_ad_username";
var connectionPassword = "your_ad_password";
// Get groups for this user
var username = "myusername";
// Split the LDAP Uri
var uri = new Uri(connectionString);
var host = uri.Host;
var container = uri.Segments.Count() >=1 ? uri.Segments[1] : "";
// Create context to connect to AD
var princContext = new PrincipalContext(ContextType.Domain, host, container, connectionUsername, connectionPassword);
// Get User
UserPrincipal user = UserPrincipal.FindByIdentity(princContext, IdentityType.SamAccountName, username);
// Browse user's groups
foreach (GroupPrincipal group in user.GetGroups())
{
Console.Out.WriteLine(group.Name);
}
You need to decode it to convert it to a string. Check the answer here about bytes literal in python3.
In [1]: b'I posted a new photo to Facebook'.decode('utf-8')
Out[1]: 'I posted a new photo to Facebook'
In a very simple words any value which has a definite size can be treated as a value type.
I think there is not similar function like data.shape
in Spark. But I will use len(data.columns)
rather than len(data.dtypes)
I am not sure if this is the best way to use GSON, but works for me. You can use some like this on the MainActivity
:
public void readJson() {
dataArrayList = new ArrayList<>();
String json = "[\n" + IOHelper.getData(this) + "\n]\n";
Log.d(TAG, json);
try{
JSONArray channelSearchEnums = new JSONArray(json);
for(int i=0; i< channelSearchEnums.length(); i++)
{
JSONObject enum = channelSearchEnums.getJSONObject(i);
ChannelSearchEnum channel = new ChannelSearchEnum(
enum.getString("updated_at"), enum.getString("fetched_at"),
enum.getString("description"), enum.getString("language"),
enum.getString("title"), enum.getString("url"),
enum.getString("icon_url"), enum.getString("logo_url"),
enum.getString("id"), enum.getString("modified"))
dataArrayList.add(channel);
}
//The code and place you want to show your data
}catch (Exception e)
{
Log.d(TAG, e.getLocalizedMessage());
}
}
You only have strings, but if you would have doubles or int, you could put getDouble
or getInt
too.
The method of IOHelper
class is the next (Here, the path is save on the internal Storage):
public static String getData(Context context) {
try {
File f = new File(context.getFilesDir().getPath() + "/" + fileName);
//check whether file exists
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (IOException e) {
Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage());
return null;
}
}
If you want more information about this, you can see this video, where I get the code of readJson()
; and this thread where I get the code of getData()
.
Having the .htaccess file on the root folder, add this line. Make sure to delete all other useless rules you tried before:
Options -Indexes
Or try:
Options All -Indexes
Two ways to do it...
GROUP BY
SELECT RES.[CUSTOMER ID], RES,NAME, SUM(INV.AMOUNT) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]
GROUP BY RES.[CUSTOMER ID], RES,NAME
OVER
SELECT RES.[CUSTOMER ID], RES,NAME,
SUM(INV.AMOUNT) OVER (PARTITION RES.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]
I realise this is an old question, but another possible consideration depending on your exact requirements is that validating on https://validator.w3.org/ generates warnings as follows:
Warning: The form role is unnecessary for element form.
You've got it nearly correct, but you haven't accounted for the this
value supplied to the inline code.
<a href="#" onclick="alert(this)">Click Me</a>
is actually closer to:
<a href="#" id="click_me">Click Me</a>
<script type="text/javascript">
document.getElementById('click_me').addEventListener("click", function(event) {
(function(event) {
alert(this);
}).call(document.getElementById('click_me'), event);
});
</script>
Inline event handlers set this
equal to the target of the event.
You can also use anonymous function in inline script
<a href="#" onclick="(function(){alert(this);})()">Click Me</a>
Adding the following line into the form worked for me:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
Application.Exit
End
will work like a charm The "END" immediately terminates further execution while "Application.Exit" closes all forms and calls.
Best regrads,
Here is the answer for those of you who need a Boostrap 3 solution.
In bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line
// tab
$('#rowTab a:first').tab('show');
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
//show selected tab / active
console.log ( $(e.target).attr('id') );
});
Better way is to use Queue class: http://docs.python.org/library/queue.html
Look at the good example code in the bottom of documentation page:
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
q = Queue()
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()
for item in source():
q.put(item)
q.join() # block until all tasks are done
The python interpreter will handle it for you, you just have to do your operations (+, -, *, /), and it will work as normal.
The int
value is unlimited.
Careful when doing division, by default the quotient is turned into float
, but float
does not support such large numbers. If you get an error message saying float
does not support such large numbers, then it means the quotient is too large to be stored in float
you’ll have to use floor division (//
).
It ignores any decimal that comes after the decimal point, this way, the result will be int
, so you can have a large number result.
>>>10//3
3
>>>10//4
2
I know this is long stagnant topic, but in case anyone searches here is how I deal with multi table foreign keys. With this technique you do not have any DBA enforced cascade operations, so please make sure you deal with DELETE
and such in your code.
Table 1 Fruit
pk_fruitid, name
1, apple
2, pear
Table 2 Meat
Pk_meatid, name
1, beef
2, chicken
Table 3 Entity's
PK_entityid, anme
1, fruit
2, meat
3, desert
Table 4 Basket (Table using fk_s)
PK_basketid, fk_entityid, pseudo_entityrow
1, 2, 2 (Chicken - entity denotes meat table, pseudokey denotes row in indictaed table)
2, 1, 1 (Apple)
3, 1, 2 (pear)
4, 3, 1 (cheesecake)
SO Op's Example would look like this
deductions
--------------
type id name
1 khce1 gold
2 khsn1 silver
types
---------------------
1 employees_ce
2 employees_sn
There is another way of getting an element by index in jQuery using CSS :nth-of-type
pseudo-class:
<script>
// css selector that describes what you need:
// ul li:nth-of-type(3)
var selector = 'ul li:nth-of-type(' + index + ')';
$(selector).css({'background-color':'#343434'});
</script>
There are other selectors that you may use with jQuery to match any element that you need.
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
I was facing the same issue on WAMP. Locate the connectors available with pip command. You can run this from any prompt if Python ENV variables are properly set.
pip search mysql-connector
mysql-connector (2.2.9) - MySQL driver written in Python
bottle-mysql-connector (0.0.4) - MySQL integration for Bottle.
mysql-connector-python (8.0.15) - MySQL driver written in Python
mysql-connector-repackaged (0.3.1) - MySQL driver written in Python
mysql-connector-async-dd (2.0.2) - mysql async connection
Run the following command to install mysql-connector
C:\Users\Admin>pip install mysql-connector
verify the installation
C:\Users\Admin>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
>>>
This solution worked for me.
Strangely enough, I don't think there is a standard solution to this problem, as the spring-security access control is expression based, not java-based. you might check the source code for DefaultMethodSecurityExpressionHandler to see if you can re-use something they are doing there
declare your date column as NOT NULL, but without a default. Then add this trigger:
USE `ddb`;
DELIMITER $$
CREATE TRIGGER `default_date` BEFORE INSERT ON `dtable` FOR EACH ROW
if ( isnull(new.query_date) ) then
set new.query_date=curdate();
end if;
$$
delimiter ;
Get-Content
(alias: gc
) is your usual option for reading a text file. You can then filter further:
gc log.txt | select -first 10 # head
gc -TotalCount 10 log.txt # also head
gc log.txt | select -last 10 # tail
gc -Tail 10 log.txt # also tail (since PSv3), also much faster than above option
gc log.txt | more # or less if you have it installed
gc log.txt | %{ $_ -replace '\d+', '($0)' } # sed
This works well enough for small files, larger ones (more than a few MiB) are probably a bit slow.
The PowerShell Community Extensions include some cmdlets for specialised file stuff (e.g. Get-FileTail).
html
<tr><td><a href="" onclick=hideRow(event)></a></td></tr>
jquery
function hideRow(event){
$(event.target || event.srcElement).parents('tr').hide();
}
You can use the following formula,
=IF(ISTEXT(REGEXEXTRACT(A1; "Bla")); "Yes";"No")
using System.IO;
using System.Text;
using System.Security.Cryptography;
public static class EncryptionHelper
{
public static string Encrypt(string clearText)
{
string EncryptionKey = "abc123";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
public static string Decrypt(string cipherText)
{
string EncryptionKey = "abc123";
cipherText = cipherText.Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
}
import UIKit
// Example iso date time
let isoDateArray = [
"2020-03-18T07:32:39.88Z",
"2020-03-18T07:32:39Z",
"2020-03-18T07:32:39.8Z",
"2020-03-18T07:32:39.88Z",
"2020-03-18T07:32:39.8834Z"
]
let dateFormatterGetWithMs = DateFormatter()
let dateFormatterGetNoMs = DateFormatter()
// Formater with and without millisecond
dateFormatterGetWithMs.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormatterGetNoMs.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
for dateString in isoDateArray {
var date: Date? = dateFormatterGetWithMs.date(from: dateString)
if (date == nil){
date = dateFormatterGetNoMs.date(from: dateString)
}
print("===========>",date!)
}
function GetDateAndTime(dt) {
var arr = new Array(dt.getDate(), dt.getMonth(), dt.getFullYear(),dt.getHours(),dt.getMinutes(),dt.getSeconds());
for(var i=0;i<arr.length;i++) {
if(arr[i].toString().length == 1) arr[i] = "0" + arr[i];
}
return arr[0] + "." + arr[1] + "." + arr[2] + " " + arr[3] + ":" + arr[4] + ":" + arr[5];
}
You need to be at MySQL version 5.6.4 or later to declare columns with fractional-second time datatypes. Not sure you have the right version? Try SELECT NOW(3)
. If you get an error, you don't have the right version.
For example, DATETIME(3)
will give you millisecond resolution in your timestamps, and TIMESTAMP(6)
will give you microsecond resolution on a *nix-style timestamp.
Read this: https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html
NOW(3)
will give you the present time from your MySQL server's operating system with millisecond precision.
If you have a number of milliseconds since the Unix epoch, try this to get a DATETIME(3) value
FROM_UNIXTIME(ms * 0.001)
Javascript timestamps, for example, are represented in milliseconds since the Unix epoch.
(Notice that MySQL internal fractional arithmetic, like * 0.001
, is always handled as IEEE754 double precision floating point, so it's unlikely you'll lose precision before the Sun becomes a white dwarf star.)
If you're using an older version of MySQL and you need subsecond time precision, your best path is to upgrade. Anything else will force you into doing messy workarounds.
If, for some reason you can't upgrade, you could consider using BIGINT
or DOUBLE
columns to store Javascript timestamps as if they were numbers. FROM_UNIXTIME(col * 0.001)
will still work OK. If you need the current time to store in such a column, you could use UNIX_TIMESTAMP() * 1000
OK, I will describe first the simplest solution which is O(N^2), where N is the size of the collection. There also exists a O(N log N) solution, which I will describe also. Look here for it at the section Efficient algorithms.
I will assume the indices of the array are from 0 to N - 1. So let's define DP[i]
to be the length of the LIS (Longest increasing subsequence) which is ending at element with index i
. To compute DP[i]
we look at all indices j < i
and check both if DP[j] + 1 > DP[i]
and array[j] < array[i]
(we want it to be increasing). If this is true we can update the current optimum for DP[i]
. To find the global optimum for the array you can take the maximum value from DP[0...N - 1]
.
int maxLength = 1, bestEnd = 0;
DP[0] = 1;
prev[0] = -1;
for (int i = 1; i < N; i++)
{
DP[i] = 1;
prev[i] = -1;
for (int j = i - 1; j >= 0; j--)
if (DP[j] + 1 > DP[i] && array[j] < array[i])
{
DP[i] = DP[j] + 1;
prev[i] = j;
}
if (DP[i] > maxLength)
{
bestEnd = i;
maxLength = DP[i];
}
}
I use the array prev
to be able later to find the actual sequence not only its length. Just go back recursively from bestEnd
in a loop using prev[bestEnd]
. The -1
value is a sign to stop.
O(N log N)
solution:Let S[pos]
be defined as the smallest integer that ends an increasing sequence of length pos
. Now iterate through every integer X
of the input set and do the following:
If X
> last element in S
, then append X
to the end of S
. This essentialy means we have found a new largest LIS
.
Otherwise find the smallest element in S
, which is >=
than X
, and change it to X
.
Because S
is sorted at any time, the element can be found using binary search in log(N)
.
Total runtime - N
integers and a binary search for each of them - N * log(N) = O(N log N)
Now let's do a real example:
Collection of integers:
2 6 3 4 1 2 9 5 8
Steps:
0. S = {} - Initialize S to the empty set
1. S = {2} - New largest LIS
2. S = {2, 6} - New largest LIS
3. S = {2, 3} - Changed 6 to 3
4. S = {2, 3, 4} - New largest LIS
5. S = {1, 3, 4} - Changed 2 to 1
6. S = {1, 2, 4} - Changed 3 to 2
7. S = {1, 2, 4, 9} - New largest LIS
8. S = {1, 2, 4, 5} - Changed 9 to 5
9. S = {1, 2, 4, 5, 8} - New largest LIS
So the length of the LIS is 5
(the size of S).
To reconstruct the actual LIS
we will again use a parent array.
Let parent[i]
be the predecessor of element with index i
in the LIS
ending at element with index i
.
To make things simpler, we can keep in the array S
, not the actual integers, but their indices(positions) in the set. We do not keep {1, 2, 4, 5, 8}
, but keep {4, 5, 3, 7, 8}
.
That is input[4] = 1, input[5] = 2, input[3] = 4, input[7] = 5, input[8] = 8.
If we update properly the parent array, the actual LIS is:
input[S[lastElementOfS]],
input[parent[S[lastElementOfS]]],
input[parent[parent[S[lastElementOfS]]]],
........................................
Now to the important thing - how do we update the parent array? There are two options:
If X
> last element in S
, then parent[indexX] = indexLastElement
. This means the parent of the newest element is the last element. We just prepend X
to the end of S
.
Otherwise find the index of the smallest element in S
, which is >=
than X
, and change it to X
. Here parent[indexX] = S[index - 1]
.
I am not quite sure if it works with ROW FORMAT serde 'com.bizo.hive.serde.csv.CSVSerde' but I guess that it should be similar to ROW FORMAT DELIMITED FIELDS TERMINATED BY ','.
In your case first row will be treated like normal row. But first field fails to be INT so all fields, for first row, will be set as NULL. You need only one intermediate step to fix it:
INSERT OVERWRITE TABLE Test
SELECT * from Test WHERE RecordId IS NOT NULL
Only one drawback is that your original csv file will be modified. I hope it helps. GL!
Factory pattern let you create an object at once at once while builder pattern let you break the creation process of an object. In this way, you can add different functionality during the creation of an object.
Read the Apple Human Interaction Guidelines for iPhone. I believe this is not approved behavior in an app.
In this answer I choose to approach the "Simple Java AES encrypt/decrypt example" main theme and not the specific debugging question because I think this will profit most readers.
This is a simple summary of my blog post about AES encryption in Java so I recommend reading through it before implementing anything. I will however still provide a simple example to use and give some pointers what to watch out for.
In this example I will choose to use authenticated encryption with Galois/Counter Mode or GCM mode. The reason is that in most case you want integrity and authenticity in combination with confidentiality (read more in the blog).
Here are the steps required to encrypt/decrypt with AES-GCM with the Java Cryptography Architecture (JCA). Do not mix with other examples, as subtle differences may make your code utterly insecure.
As it depends on your use-case, I will assume the simplest case: a random secret key.
SecureRandom secureRandom = new SecureRandom();
byte[] key = new byte[16];
secureRandom.nextBytes(key);
SecretKey secretKey = SecretKeySpec(key, "AES");
Important:
SecureRandom
An initialization vector (IV) is used so that the same secret key will create different cipher texts.
byte[] iv = new byte[12]; //NEVER REUSE THIS IV WITH SAME KEY
secureRandom.nextBytes(iv);
Important:
SecureRandom
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv); //128 bit auth tag length
cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);
byte[] cipherText = cipher.doFinal(plainText);
Important:
CipherInputStream
when encrypting large chunks of datacipher.updateAAD(associatedData);
More here.Just append IV and ciphertext. As stated above, the IV doesn't need to be secret.
ByteBuffer byteBuffer = ByteBuffer.allocate(iv.length + cipherText.length);
byteBuffer.put(iv);
byteBuffer.put(cipherText);
byte[] cipherMessage = byteBuffer.array();
Optionally encode with Base64 if you need a string representation. Either use Android's or Java 8's built-in implementation (do not use Apache Commons Codec - it's an awful implementation). Encoding is used to "convert" byte arrays to string representation to make it ASCII safe e.g.:
String base64CipherMessage = Base64.getEncoder().encodeToString(cipherMessage);
If you have encoded the message, first decode it to byte array:
byte[] cipherMessage = Base64.getDecoder().decode(base64CipherMessage)
Important:
Initialize the cipher and set the same parameters as with the encryption:
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
//use first 12 bytes for iv
AlgorithmParameterSpec gcmIv = new GCMParameterSpec(128, cipherMessage, 0, 12);
cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmIv);
//use everything from 12 bytes on as ciphertext
byte[] plainText = cipher.doFinal(cipherMessage, 12, cipherMessage.length - 12);
Important:
cipher.updateAAD(associatedData);
if you added it during encryption.A working code snippet can be found in this gist.
Note that most recent Android (SDK 21+) and Java (7+) implementations should have AES-GCM. Older versions may lack it. I still choose this mode, since it is easier to implement in addition to being more efficient compared to similar mode of Encrypt-then-Mac (with e.g. AES-CBC + HMAC). See this article on how to implement AES-CBC with HMAC.
If you'd rather transform your array, then the iterator
parameter of underscore's map
function is also passed the index as a second argument. So:
_.map([1, 4, 2, 66, 444, 9], function(value, index){ return index + ':' + value; });
... returns:
["0:1", "1:4", "2:2", "3:66", "4:444", "5:9"]
You can call dispose()
on the current window and setVisible(true)
on the one you want to display.
As answered before, it's currently still being considered but it has been dead in the water for a few years by now.
Building on the existing answers, here's the most concise manual version I can think of:
function val<T>(valueSupplier: () => T): T {
try { return valueSupplier(); } catch (err) { return undefined; }
}
let obj1: { a?: { b?: string }} = { a: { b: 'c' } };
console.log(val(() => obj1.a.b)); // 'c'
obj1 = { a: {} };
console.log(val(() => obj1.a.b)); // undefined
console.log(val(() => obj1.a.b) || 'Nothing'); // 'Nothing'
obj1 = {};
console.log(val(() => obj1.a.b) || 'Nothing'); // 'Nothing'
obj1 = null;
console.log(val(() => obj1.a.b) || 'Nothing'); // 'Nothing'
It simply silently fails on missing property errors. It falls back to the standard syntax for determining default value, which can be omitted completely as well.
Although this works for simple cases, if you need more complex stuff such as calling a function and then access a property on the result, then any other errors are swallowed as well. Bad design.
In the above case, an optimized version of the other answer posted here is the better option:
function o<T>(obj?: T, def: T = {} as T): T {
return obj || def;
}
let obj1: { a?: { b?: string }} = { a: { b: 'c' } };
console.log(o(o(o(obj1).a)).b); // 'c'
obj1 = { a: {} };
console.log(o(o(o(obj1).a)).b); // undefined
console.log(o(o(o(obj1).a)).b || 'Nothing'); // 'Nothing'
obj1 = {};
console.log(o(o(o(obj1).a)).b || 'Nothing'); // 'Nothing'
obj1 = null;
console.log(o(o(o(obj1).a)).b || 'Nothing'); // 'Nothing'
A more complex example:
o(foo(), []).map((n) => n.id)
You can also go the other way and use something like Lodash' _.get()
. It is concise, but the compiler won't be able to judge the validity of the properties used:
console.log(_.get(obj1, 'a.b.c'));
import turtle
wn = turtle.Screen()
turtle = turtle.Turtle()
def printLetter():
print("a")
turtle.listen()
turtle.onkey(printLetter, "a")
Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.
If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow
How to convert <select> dropdown into an unordered list using jquery?
Data contract: It specifies that your entity class is ready for Serialization process.
Data members: It specifies that the particular field is part of the data contract and it can be serialized.
Send the signal to all the processes in group
self.proc = Popen(commands,
stdout=PIPE,
stderr=STDOUT,
universal_newlines=True,
preexec_fn=os.setsid)
os.killpg(os.getpgid(self.proc.pid), signal.SIGHUP)
os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)
Technically you can write code in a .NET language and use the Mono Framework (http://www.mono-project.com/) to run it on the iPhone. I haven't ever seen someone do this from scratch, but the folks that write the Unity Game Development platform (http://unity3d.com/) use it to make their games iPhone-compatible. The game itself is written in .NET, and then they provide an iPhone shell with the Mono frameworks that allows everything to run on the iPhone. I don't know whether they've contributed all of their modifications to Mono back to the open-source repository, but if you're serious about writing iPhone apps outside the Mac environment, it might be possible.
That said, I think you could dump weeks into getting that to work, and it might be best to invest in a Mac instead :-)
Another more efficient way to do is just use @Value
@Value("classpath:sss.json")
private Resource resource;
and after that you can just get the file this way
File file = resource.getFile();
Using pdfbox we can achive this
Example :
public static void main(String args[]) {
PDFParser parser = null;
PDDocument pdDoc = null;
COSDocument cosDoc = null;
PDFTextStripper pdfStripper;
String parsedText;
String fileName = "E:\\Files\\Small Files\\PDF\\JDBC.pdf";
File file = new File(fileName);
try {
parser = new PDFParser(new FileInputStream(file));
parser.parse();
cosDoc = parser.getDocument();
pdfStripper = new PDFTextStripper();
pdDoc = new PDDocument(cosDoc);
parsedText = pdfStripper.getText(pdDoc);
System.out.println(parsedText.replaceAll("[^A-Za-z0-9. ]+", ""));
} catch (Exception e) {
e.printStackTrace();
try {
if (cosDoc != null)
cosDoc.close();
if (pdDoc != null)
pdDoc.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
I got this message when I tried to redirect as:
public function validateLogin(LoginRequest $request){
//
return redirect()->route('sesion.iniciar')
->withErrors($request)
->withInput();
When the right way is:
public function validateLogin(LoginRequest $request){
//
return redirect()->route('sesion.iniciar')
->withErrors($request->messages())
->withInput();
java.sql.Timestamp
.valueOf( // Class-method parses SQL-style formatted date-time strings.
"2007-11-11 12:13:14"
) // Returns a `Timestamp` object.
.toInstant() // Converts from terrible legacy classes to modern *java.time* class.
java.sql.Timestamp.valueOf
parses SQL formatIf you can use the full four digits for the year, your input string of 2007-11-11 12:13:14
would be in standard SQL format assuming this value is meant to be in UTC time zone.
The java.sql.Timestamp
class has a valueOf
method to directly parse such strings.
String input = "2007-11-11 12:13:14" ;
java.sql.Timestamp ts = java.sql.Timestamp.valueOf( input ) ;
In Java 8 and later, the java.time framework makes it easier to verify the results. The j.s.Timestamp class has a nasty habit of implicitly applying your JVM’s current default timestamp when generating a string representation via its toString
method. In contrast, the java.time classes by default use the standard ISO 8601 formats.
System.out.println( "Output: " + ts.toInstant().toString() );
You need to define the Filesystem to read resource from jar file as mentioned in https://docs.oracle.com/javase/8/docs/technotes/guides/io/fsp/zipfilesystemprovider.html. I success to read resource from jar file with below codes:
Map<String, Object> env = new HashMap<>();
try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
Path path = fs.getPath("/path/myResource");
try (Stream<String> lines = Files.lines(path)) {
....
}
}
strcmp will return different values based on the environment it is running(Linux/Windows)!
The reason is the that it has a bug as the bug report says https://bugs.php.net/bug.php?id=53999
Please handle with care!!Thank you.
Since I had a similar situation, I thought I'd share my situation and how these answers helped me (thanks everyone).
So I decided to work locally by amending my last commit every time I wanted to save my progress on the main branch (I know, I should've branched out, committed on that, kept pushing and later merge back to master).
One late night, in paranoid fear of loosing my progress to hardware failure or something out of the ether, I decided to push master to origin. Later I kept amending my local master branch and when I decided it's time to push again, I was faced with different master branches and found out I can't amend origin/upstream (duh!) like I can local development branches.
So I didn't checkout master locally because I already was after a commit. Master was unchanged. I didn't even need to reset --hard, my current commit was OK.
I just forced push to origin, without even specifying what commit I wanted to force on master since in this case it's whatever HEAD is at. Checked git diff master..origin/master
so there weren't any differences and that's it. All fixed. Thanks! (I know, I'm a git newbie, please forgive!).
So if you're already OK with your master branch locally, just:
git push --force origin master
git diff master..origin/master
Please add reference of System.Web.Extensions and add this namespace using System.Web.Script.Serialization;
at top:
public static void EasyJson()
{
var jsonText = @"{
""some_number"": 108.541,
""date_time"": ""2011-04-13T15:34:09Z"",
""serial_number"": ""SN1234""
}";
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);
Console.WriteLine(dict["some_number"]);
Console.ReadLine();
}
Please add reference of System.Web.Extensions and add this namespace using System.Web.Script.Serialization;
at top:
public static void ComplexJson()
{
var jsonText = @"{
""some_number"": 108.541,
""date_time"": ""2011-04-13T15:34:09Z"",
""serial_number"": ""SN1234"",
""more_data"": {
""field1"": 1.0,
""field2"": ""hello""
}
}";
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);
Console.WriteLine(dict["some_number"]);
Console.WriteLine(dict["more_data"]["field2"]);
Console.ReadLine();
}
The datetime
module is your friend:
import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40
You don't need separate variables, the attributes on the returned datetime
object have all you need.
generally . doesn't match newlines, so try ((.|\n)*)<foobar>
Think about somebody doing help(yourmodule)
at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help
in terms of amount of information). So if you have in x.py
:
"""This module does blah blah."""
class Blah(object):
"""This class does blah blah."""
then:
>>> import x; help(x)
shows:
Help on module x:
NAME
x - This module does blah blah.
FILE
/tmp/x.py
CLASSES
__builtin__.object
Blah
class Blah(__builtin__.object)
| This class does blah blah.
|
| Data and other attributes defined here:
|
| __dict__ = <dictproxy object>
| dictionary for instance variables (if defined)
|
| __weakref__ = <attribute '__weakref__' of 'Blah' objects>
| list of weak references to the object (if defined)
As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).
I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.
I've used the Visual Studio extension "Full Rename Project" to successfully rename projects in an ASP.NET Core 2 solution.
I used ReSharper then to adjust the namespace (right click on project, refactor, adjust namespaces...)
Also be careful with double-quotes -- on the Unix shell this expands variables. Some are obvious (like $foo
and \t
) but some are not (like !foo
).
For safety, use single-quotes!
well distinct can be slower than group by on some occasions in postgres (dont know about other dbs).
tested example:
postgres=# select count(*) from (select distinct i from g) a;
count
10001
(1 row)
Time: 1563,109 ms
postgres=# select count(*) from (select i from g group by i) a;
count
10001
(1 row)
Time: 594,481 ms
http://www.pgsql.cz/index.php/PostgreSQL_SQL_Tricks_I
so be careful ... :)
Interpreted language is executed at the run time according to the instructions like in shell scripting and compiled language is one which is compiled (changed into Assembly language, which CPU can understand ) and then executed like in c++.
Those who are using Java 7.0 or below version can refer the code which I used here and it works.
public class WaitTest {
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public void waitHere(long waitTime) {
System.out.println("wait started...");
lock.lock();
try {
condition.await(waitTime, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.unlock();
System.out.println("wait ends here...");
}
public static void main(String[] args) {
//Your Code
new WaitTest().waitHere(10);
//Your Code
}
}
Another simple solution using the AppCompatButton
<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/Widget.AppCompat.Button.Colored"
app:backgroundTint="@color/red"
android:text="UNINSTALL" />
Just invert the indexes' order like this:
for (int j = 0; j<array[0].length; j++){
for (int i = 0; i<array.length; i++){
because all rows has same amount of columns you can use this condition j < array[0].lengt in first for condition due to the fact you are iterating over a matrix
Java now has a pretty good built-in date library, java.time bundled with Java 8.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Foo {
public static void main(String[] args) {
DateTimeFormatter format =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.minusDays(7);
System.out.println(String.format(
"Now: %s\nThen: %s",
now.format(format),
then.format(format)
));
/*
Example output:
Now: 2014-05-09T14:51:48Z
Then: 2014-05-02T14:51:48Z
*/
}
}
See here: Search Path
Summary:
#include <stdio.h>
When the include file is in brackets the preprocessor first searches in paths specified via the -I flag. Then it searches the standard include paths (see the above link, and use the -v flag to test on your system).
#include "myFile.h"
When the include file is in quotes the preprocessor first searches in the current directory, then paths specified by -iquote, then -I paths, then the standard paths.
-nostdinc can be used to prevent the preprocessor from searching the standard paths at all.
Environment variables can also be used to add search paths.
When compiling if you use the -v flag you can see the search paths used.
To answer your question - nginx picks the first server if there's no match. See documentation:
If its value does not match any server name, or the request does not contain this header field at all, then nginx will route the request to the default server for this port. In the configuration above, the default server is the first one...
Now, if you wanted to have a default catch-all server that, say, responds with 404 to all requests, then here's how to do it:
server {
listen 80 default_server;
listen 443 ssl default_server;
server_name _;
ssl_certificate <path to cert>
ssl_certificate_key <path to key>
return 404;
}
Note that you need to specify certificate/key (that can be self-signed), otherwise all SSL connections will fail as nginx will try to accept connection using this default_server and won't find cert/key.
if you are anything like me coming from a google search and looking to remove an html element with cool animation, then this could help you:
$(document).ready(function() {_x000D_
_x000D_
var $deleteButton = $('.deleteItem');_x000D_
_x000D_
$deleteButton.on('click', function(event) {_x000D_
_x000D_
event.preventDefault();_x000D_
_x000D_
var $button = $(this);_x000D_
_x000D_
if(confirm('Are you sure about this ?')) {_x000D_
_x000D_
var $item = $button.closest('tr.item');_x000D_
_x000D_
$item.addClass('removed-item')_x000D_
_x000D_
.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {_x000D_
_x000D_
$(this).remove();_x000D_
});_x000D_
}_x000D_
_x000D_
});_x000D_
_x000D_
});
_x000D_
/**_x000D_
* Credit to Sara Soueidan_x000D_
* @link https://github.com/SaraSoueidan/creative-list-effects/blob/master/css/styles-3.css_x000D_
*/_x000D_
_x000D_
.removed-item {_x000D_
-webkit-animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29);_x000D_
-o-animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29);_x000D_
animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29)_x000D_
}_x000D_
_x000D_
@keyframes removed-item-animation {_x000D_
0% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(0);_x000D_
-ms-transform: translateX(0);_x000D_
-o-transform: translateX(0);_x000D_
transform: translateX(0)_x000D_
}_x000D_
_x000D_
30% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(50px);_x000D_
-ms-transform: translateX(50px);_x000D_
-o-transform: translateX(50px);_x000D_
transform: translateX(50px)_x000D_
}_x000D_
_x000D_
80% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(-800px);_x000D_
-ms-transform: translateX(-800px);_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 0;_x000D_
-webkit-transform: translateX(-800px);_x000D_
-ms-transform: translateX(-800px);_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
}_x000D_
_x000D_
@-webkit-keyframes removed-item-animation {_x000D_
0% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(0);_x000D_
transform: translateX(0)_x000D_
}_x000D_
_x000D_
30% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(50px);_x000D_
transform: translateX(50px)_x000D_
}_x000D_
_x000D_
80% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 0;_x000D_
-webkit-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
}_x000D_
_x000D_
@-o-keyframes removed-item-animation {_x000D_
0% {_x000D_
opacity: 1;_x000D_
-o-transform: translateX(0);_x000D_
transform: translateX(0)_x000D_
}_x000D_
_x000D_
30% {_x000D_
opacity: 1;_x000D_
-o-transform: translateX(50px);_x000D_
transform: translateX(50px)_x000D_
}_x000D_
_x000D_
80% {_x000D_
opacity: 1;_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 0;_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table class="table table-striped table-bordered table-hover">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>id</th>_x000D_
<th>firstname</th>_x000D_
<th>lastname</th>_x000D_
<th>@twitter</th>_x000D_
<th>action</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
_x000D_
<tr class="item">_x000D_
<td>1</td>_x000D_
<td>Nour-Eddine</td>_x000D_
<td>ECH-CHEBABY</td>_x000D_
<th>@__chebaby</th>_x000D_
<td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
</tr>_x000D_
_x000D_
<tr class="item">_x000D_
<td>2</td>_x000D_
<td>John</td>_x000D_
<td>Doe</td>_x000D_
<th>@johndoe</th>_x000D_
<td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
</tr>_x000D_
_x000D_
<tr class="item">_x000D_
<td>3</td>_x000D_
<td>Jane</td>_x000D_
<td>Doe</td>_x000D_
<th>@janedoe</th>_x000D_
<td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Quite simply the number is the precision of the timestamp, the fraction of a second held in the column:
SQL> create table t23
2 (ts0 timestamp(0)
3 , ts3 timestamp(3)
4 , ts6 timestamp(6)
5 )
6 /
Table created.
SQL> insert into t23 values (systimestamp, systimestamp, systimestamp)
2 /
1 row created.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
SQL>
If we don't specify a precision then the timestamp defaults to six places.
SQL> alter table t23 add ts_def timestamp;
Table altered.
SQL> update t23
2 set ts_def = systimestamp
3 /
1 row updated.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
SQL>
Note that I'm running on Linux so my TIMESTAMP
column actually gives me precision to six places i.e. microseconds. This would also be the case on most (all?) flavours of Unix. On Windows the limit is three places i.e. milliseconds. (Is this still true of the most modern flavours of Windows - citation needed).
As might be expected, the documentation covers this. Find out more.
"when you create timestamp(9) this gives you nanos right"
Only if the OS supports it. As you can see, my OEL appliance does not:
SQL> alter table t23 add ts_nano timestamp(9)
2 /
Table altered.
SQL> update t23 set ts_nano = systimestamp(9)
2 /
1 row updated.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
TS_NANO
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
24-JAN-12 08.28.03.990557000 AM
SQL>
(Those trailing zeroes could be a coincidence but they aren't.)
I use this method to solve this problem Maybe you can try it
"Enable ssh-agent"
Install it
Enable ssh-agent
C:\Program Files\Git\cmd
start-ssh-agent
The message disapper after I agent enabled Hope this will help you
First we should know the order of execution of Clauses i.e FROM > WHERE > GROUP BY > HAVING > DISTINCT > SELECT > ORDER BY. Since WHERE Clause gets executed before GROUP BY Clause the records cannot be filtered by applying WHERE to a GROUP BY applied records.
"HAVING is same as the WHERE clause but is applied on grouped records".
first the WHERE clause fetches the records based on the condition then the GROUP BY clause groups them accordingly and then the HAVING clause fetches the group records based on the having condition.
After trying more than hundred of tricks, finally got success.
I removed all java.exe
, javaw.exe
and javaws.exe
from my
Windows\System32
and
Windows\SysWOW64
folder. [Try step 2 if you have x64 system (Win 7 64 bits)]
It appears to be a known issue.
http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html
http://bugs.mysql.com/bug.php?id=16757
Many IN queries can be re-written as (left outer) joins and an IS (NOT) NULL of some sort. for example
SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)
can be re-written as
SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID
or
SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)
can be
SELECT FOO.* FROM FOO
LEFT OUTER JOIN FOO2
ON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL
Step I: include the file and plugin
../jspdf.plugin.addimage.js
Step II: build PDF content var doc = new jsPDF();
doc.setFontSize(12);
doc.text(35, 25, "Welcome to JsPDF");
doc.addImage(imgData, 'JPEG', 15, 40, 386, 386);
Step III: display image in new window
doc.output('dataurlnewwindow');
Stepv IV: save data
var output = doc.output();
return btoa( output);
@Html.CheckBox("yourId", true, new { value = Model.Ischecked })
This will certainly work
Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.
function myFunction() {_x000D_
var selchbox = [];_x000D_
var inputfields = document.getElementsByName("myCheck");_x000D_
var ar_inputflds = inputfields.length;_x000D_
_x000D_
for (var i = 0; i < ar_inputflds; i++) {_x000D_
if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
selchbox.push(inputfields[i].value);_x000D_
}_x000D_
return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
var selchb = myFunction();_x000D_
console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
answer = “True”
myvars = “the answer is” + answer
print(myvars)
That should give you the answer is True easily as you have stored answer as a string by using the quotation marks
As a key-hardened salted hash, using a secure algorithm such as sha-512.
If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.
I had gone this way:
scrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return isBlockedScrollView;
}
});
If you find yourself overriding (non-abstract) methods very often, you probably want to take a look at your design. It is very useful when the compiler would not otherwise catch the error. For instance trying to override initValue() in ThreadLocal, which I have done.
Using @Override when implementing interface methods (1.6+ feature) seems a bit overkill for me. If you have loads of methods some of which override and some don't, that probably bad design again (and your editor will probably show which is which if you don't know).
Although a set is the easiest way, you could also use a dict and use some_dict.has(key)
to populate a dictionary with only unique keys and values.
Assuming you have already populated words[]
with input from the user, create a dict mapping the unique words in the list to a number:
word_map = {}
i = 1
for j in range(len(words)):
if not word_map.has_key(words[j]):
word_map[words[j]] = i
i += 1
num_unique_words = len(new_map) # or num_unique_words = i, however you prefer
As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.
You need to wrap your .myTestClass
inside an element and apply the styles to descendants by adding .wrapper *
descendant selector. Then, add .myTestClass > *
child selector to apply the style to the elements children, not its grand children. For example like this:
JSFiddle - DEMO
.wrapper * {_x000D_
color: blue;_x000D_
margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
color:red;_x000D_
margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="myTestClass">Text 0_x000D_
<div>Text 1</div>_x000D_
<span>Text 1</span>_x000D_
<div>Text 1_x000D_
<p>Text 2</p>_x000D_
<div>Text 2</div>_x000D_
</div>_x000D_
<p>Text 1</p>_x000D_
</div>_x000D_
<div>Text 0</div>_x000D_
</div>
_x000D_
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'prev_text' >' Previous','post_type' => 'page', 'posts_per_page' => 5, 'paged' => $paged );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
//get all pages
the_ID();
the_title();
//if you want specific page of content then write
if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
{
echo get_the_ID();
the_title();
the_content();
}
endwhile;
//if you want specific page of content then write in loop
if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
{
echo get_the_ID();
the_title();
the_content();
}
Addressing the question as updated.
#...part of script without redirection...
{
#...part of script with redirection...
} > file1 2>file2 # ...and others as appropriate...
#...residue of script without redirection...
The braces '{ ... }' provide a unit of I/O redirection. The braces must appear where a command could appear - simplistically, at the start of a line or after a semi-colon. (Yes, that can be made more precise; if you want to quibble, let me know.)
You are right that you can preserve the original stdout and stderr with the redirections you showed, but it is usually simpler for the people who have to maintain the script later to understand what's going on if you scope the redirected code as shown above.
The relevant sections of the Bash manual are Grouping Commands and I/O Redirection. The relevant sections of the POSIX shell specification are Compound Commands and I/O Redirection. Bash has some extra notations, but is otherwise similar to the POSIX shell specification.
Just a few lines of example code to show the difference between numpy.array and numpy.ndarray
Warm up step: Construct a list
a = [1,2,3]
Check the type
print(type(a))
You will get
<class 'list'>
Construct an array (from a list) using np.array
a = np.array(a)
Or, you can skip the warm up step, directly have
a = np.array([1,2,3])
Check the type
print(type(a))
You will get
<class 'numpy.ndarray'>
which tells you the type of the numpy array is numpy.ndarray
You can also check the type by
isinstance(a, (np.ndarray))
and you will get
True
Either of the following two lines will give you an error message
np.ndarray(a) # should be np.array(a)
isinstance(a, (np.array)) # should be isinstance(a, (np.ndarray))
On your backEnd, you should add:
@RequestMapping(value="/blabla", produces="text/plain" , method = RequestMethod.GET)
On the frontEnd (Service):
methodBlabla()
{
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.get(this.url,{ headers, responseType: 'text'});
}
[print(a) for a in list]
will give a bunch of None types at the end though it prints out all the items
...JavaScript's parser tries to parse the dot notation on a number as a floating point literal.
2..toString(); // the second point is correctly recognized
2 .toString(); // note the space left to the dot
(2).toString(); // 2 is evaluated first
If you want it visually formatted to two decimals as a string (for output) use toFixed()
:
var priceString = someValue.toFixed(2);
The answer by @David has two problems:
It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999
instead of "134.20"
.
If your value is an integer or rounds to one tenth, you will not see the additional decimal value:
var n = 1.099;
(Math.round( n * 100 )/100 ).toString() //-> "1.1"
n.toFixed(2) //-> "1.10"
var n = 3;
(Math.round( n * 100 )/100 ).toString() //-> "3"
n.toFixed(2) //-> "3.00"
And, as you can see above, using toFixed()
is also far easier to type. ;)
Postman is a good solution and so is php fiddle. However to avoid putting in the GCM URL and the header information every time, you can also use this nifty GCM Notification Test Tool
function x() {}
is equivalent (or very similar) to
var x = function() {}
unless I'm mistaken.
So there is nothing funny going on.
Add the location of your git-upload-pack
to the remote git user's .bashrc file.
The array declaration has incorrect syntax. Try the following, instead:
var numbers = [ 1, 2, 3, 4, 5]
The loop part seems right
$.each(numbers, function(val, text) {
$('#items').append( $('<option></option>').val(val).html(text) )
}); // there was also a ) missing here
As @Reigel did seems to add a bit more performance (it is not noticeable on such small arrays)
I was able to fix this by following the steps in this article: http://www.mikesdotnetting.com/article/280/solved-the-microsoft-ace-oledb-12-0-provider-is-not-registered-on-the-local-machine
The key point for me was this:
When debugging with IIS,
by default, Visual Studio uses the 32-bit version. You can change this from within Visual Studio by going to Tools » Options » Projects And Solutions » Web Projects » General, and choosing
"Use the 64 bit version of IIS Express for websites and projects"
After checking that option, then setting the platform target of my project back to "Any CPU" (i had set it to x86 somewhere in the troubleshooting process), i was able to overcome the error.
var val = $.parseJSON(data);
if(val.success == true)
{
setTimeout(function(){ location.reload(); }, 5000);
}
onchange
will work only if the value of the textbox changed compared to the value it had before, so for the first time it won't work because the state didn't change.
So it is better to use onblur
event or on submitting the form.
function checkTextField(field) {_x000D_
document.getElementById("error").innerText =_x000D_
(field.value === "") ? "Field is empty." : "Field is filled.";_x000D_
}
_x000D_
<input type="text" onblur="checkTextField(this);" />_x000D_
<p id="error"></p>
_x000D_
You are probably looking for:
!toDate.before(currentDate)
before() and after() test whether the date is strictly before or after. So you have to take the negation of the other one to get non strict behaviour.
we can use target = blank to open in new tab
<a href="https://www.google.co.in/" target="blank">click Here </a>
I have a similar request from a client who wants to have the header, page numbers, and html footer removed. In this case, the client is presenting an HTML page that can double as a formal certificate. The added URL, page, and, header, are irrelevant and lead to a less-than-pleasing final product. In some ways, it just looks cheap.
Media=Print has not been able to disable these browser defaults. The only workaround is to tell the user to click the "Gear" button and toggle those items on/off. Seriously, I had no idea I could do that for 20 years (and we think the typical user will have a clue to click the toggle button?).
If CSS supports Media=Print, it should support the ability to control the entire end-user print experience. I appreciate that the browsers provide the added fields, but, why not allow CSS to control the overall print experience-if that is what's desired. A 90% solution could be 100% with three more fields! A simple:
#BrowserPrintDefaults{display:none}
would suffice.
Again, it's not a matter whether or not the end-user wants to print it out or not (maybe your client is very private and doesn't want printed URLs floating around. Or maybe a executive team uses a private collaboration sites?). Glad to defend the end-user, but if somebody is seeking an answer, don't respond saying it's the right of the end-user to show or hide. Sometimes it's the right of the client paying the bills.
as noted by @tripleee, this is tangential, at best.
still, in case you arrived here searching for something like that (as i did), here is my solution
having to deal with user acessible configuration files, i use this function :
function isTrue() {
if [[ "${@^^}" =~ ^(TRUE|OUI|Y|O$|ON$|[1-9]) ]]; then return 0;fi
return 1
}
wich can be used like that
if isTrue "$whatever"; then..
You can alter the "truth list" in the regexp, the one in this sample is french compatible and considers strings like "Yeah, yup, on,1, Oui,y,true to be "True".
note that the '^^' provides case insensivity
Received SQLSTATE 01000 in the following error message below:
SQL Agent - Jobs Failed: The SQL Agent Job "LiteSpeed Backup Full" has failed with the message "The job failed. The Job was invoked by User X. The last step to run was step 1 (Step1). NOTE: Failed to notify via email. - Executed as user: X. LiteSpeed(R) for SQL Server Version 6.5.0.1460 Copyright 2011 Quest Software, Inc. [SQLSTATE 01000] (Message 1) LiteSpeed for SQL Server could not open backup file: (N:\BACKUP2\filename.BAK). The previous system message is the reason for the failure. [SQLSTATE 42000] (Error 60405). The step failed."
In my case this was related to permission on drive N following an SQL Server failover on an Active/Passive SQL cluster.
All SQL resources where failed over to the seconary resouce and back to the preferred node following maintenance. When the Quest LiteSpeed job then executed on the preferred node it was clear the previous permissions for SQL server user X had been lost on drive N and SQLSTATE 10100 was reported.
Simply added the permissions again to the backup destination drive and the issue was resolved.
Hope that helps someone.
Windows 2008 Enterprise
SQL Server 2008 Active/Passive cluster.
Whatever I understood from my learning and what I think it is is here. I am Quoting some part from a book i learnt this things. Nexus Repository Manager and Nexus Repository Manager OSS started as a repository manager supporting the Maven repository format. While it supports many other repository formats now, the Maven repository format is still the most common and well supported format for build and provisioning tools running on the JVM and beyond. This chapter shows example configurations for using the repository manager with Apache Maven and a number of other tools. The setups take advantage of merging many repositories and exposing them via a repository group. Setting this up is documented in the chapter in addition to the configuration used by specific tools.
This can easily be done manually with the Windows Task Scheduler.
Then, create a batch file that contains the following:
cd C:\path\to\project\root
call C:\Users\Username\AppData\Roaming\npm\forever.cmd start server.js
exit 0
Lastly, create a scheduled task that runs when you log on. This task should call the batch file.
Here is a complete screenshot example that works with chrome in 2021. The end result is a blob ready to be transmitted. Flow is: request media > grab frame > draw to canvas > transfer to blob. If you want to do it more memory efficient explore OffscreenCanvas or possibly ImageBitmapRenderingContext
https://jsfiddle.net/v24hyd3q/1/
// Request media
navigator.mediaDevices.getDisplayMedia().then(stream =>
{
// Grab frame from stream
let track = stream.getVideoTracks()[0];
let capture = new ImageCapture(track);
capture.grabFrame().then(bitmap =>
{
// Stop sharing
track.stop();
// Draw the bitmap to canvas
canvas.width = bitmap.width;
canvas.height = bitmap.height;
canvas.getContext('2d').drawImage(bitmap, 0, 0);
// Grab blob from canvas
canvas.toBlob(blob => {
// Do things with blob here
console.log('output blob:', blob);
});
});
})
.catch(e => console.log(e));
I have created a PHP function that could extract attributes of any HTML tags. It also can handle attributes like disabled
that has no value, and also can determine whether the tag is a stand-alone tag (has no closing tag) or not (has a closing tag) by checking the content
result:
/*! Based on <https://github.com/mecha-cms/cms/blob/master/system/kernel/converter.php> */
function extract_html_attributes($input) {
if( ! preg_match('#^(<)([a-z0-9\-._:]+)((\s)+(.*?))?((>)([\s\S]*?)((<)\/\2(>))|(\s)*\/?(>))$#im', $input, $matches)) return false;
$matches[5] = preg_replace('#(^|(\s)+)([a-z0-9\-]+)(=)(")(")#i', '$1$2$3$4$5<attr:value>$6', $matches[5]);
$results = array(
'element' => $matches[2],
'attributes' => null,
'content' => isset($matches[8]) && $matches[9] == '</' . $matches[2] . '>' ? $matches[8] : null
);
if(preg_match_all('#([a-z0-9\-]+)((=)(")(.*?)("))?(?:(\s)|$)#i', $matches[5], $attrs)) {
$results['attributes'] = array();
foreach($attrs[1] as $i => $attr) {
$results['attributes'][$attr] = isset($attrs[5][$i]) && ! empty($attrs[5][$i]) ? ($attrs[5][$i] != '<attr:value>' ? $attrs[5][$i] : "") : $attr;
}
}
return $results;
}
$test = array(
'<div class="foo" id="bar" data-test="1000">',
'<div>',
'<div class="foo" id="bar" data-test="1000">test content</div>',
'<div>test content</div>',
'<div>test content</span>',
'<div>test content',
'<div></div>',
'<div class="foo" id="bar" data-test="1000"/>',
'<div class="foo" id="bar" data-test="1000" />',
'< div class="foo" id="bar" data-test="1000" />',
'<div class id data-test>',
'<id="foo" data-test="1000">',
'<id data-test>',
'<select name="foo" id="bar" empty-value-test="" selected disabled><option value="1">Option 1</option></select>'
);
foreach($test as $t) {
var_dump($t, extract_html_attributes($t));
echo '<hr>';
}
If you read the help for vector
(or numeric
or logical
or character
or integer
or double
, 'raw' or complex
etc ) then you will see that they all have a length
(or length.out
argument which defaults to 0
Therefore
numeric()
logical()
character()
integer()
double()
raw()
complex()
vector('numeric')
vector('character')
vector('integer')
vector('double')
vector('raw')
vector('complex')
All return 0 length vectors of the appropriate atomic modes.
# the following will also return objects with length 0
list()
expression()
vector('list')
vector('expression')
I store encoded HTML in the database.
Imho you should not store your data html-encoded in the database. Just store in plain text (not encoded) and just display your data like this and your html will be automatically encoded:
<div class='content'>
@Model.Content
</div>
There's a simpler way to do this:
$(newHtml).appendTo('#myDiv').effects(...);
This turns things around by first creating newHtml
with jQuery(html [, ownerDocument ])
, and then using appendTo(target)
(note the "To
" bit) to add that it to the end of #mydiv
.
Because you now start with $(newHtml)
the end result of appendTo('#myDiv')
is that new bit of html, and the .effects(...)
call will be on that new bit of html too.
Currently you can't access the arrays named name and country, because they are member variables of your Athelete class.
Based on what it looks like you're trying to do, this will not work.
These arrays belong in your main class.
I think the simpliest is just to convert a string into a date object and convert it back to a string. The given date string is fine if both strings still match.
public boolean isDateValid(String dateString, String pattern)
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
if (sdf.format(sdf.parse(dateString)).equals(dateString))
return true;
}
catch (ParseException pe) {}
return false;
}
You can use GeometryReader in a handy extension to fill the parent
extension View {
func fillParent(alignment:Alignment = .center) -> some View {
return GeometryReader { geometry in
self
.frame(width: geometry.size.width,
height: geometry.size.height,
alignment: alignment)
}
}
}
so using the requested example, you get
struct ContentView : View {
var body: some View {
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.lineLimit(nil)
.font(.body)
}
.fillParent(alignment:.topLeading)
.background(Color.red)
}
}
(note the spacer is no longer needed)
this is a sample case, which will make sense I believe!
node('master'){
stage('stage1'){
def commit = sh (returnStdout: true, script: '''echo hi
echo bye | grep -o "e"
date
echo lol''').split()
echo "${commit[-1]} "
}
}
What am I doing incorrectly?
You have to convert html to javascript object, and then as a second step to json throug JSON.Stringify.
How can I receive a json object in the controller?
View:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://raw.githubusercontent.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializejson.js"></script>
var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
$.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });
<form id="form1" method="post">
<input name="OrderDate" type="text" /><br />
<input name="Item[0][Id]" type="text" /><br />
<input name="Item[1][Id]" type="text" /><br />
<button id="btn" onclick="btnClick()">Button</button>
</form>
Controller:
public void PostRawJson(string json)
{
var order = System.Web.Helpers.Json.Decode(json);
var orderDate = order.OrderDate;
var secondOrderId = order.Item[1].Id;
}
I installed the latest version of json:
gem install json
Then deleted the line json(1.8.1) from the Gemfile.lock and did a
bundle install
And then the Gemfile.lock file uses json(1.8.3) without erros
I've gotten that error twice:
1) When I wrote:
var app = module('flapperNews', []);
instead of:
var app = angular.module('flapperNews', []);
2) When I copy and pasted some html, and the controller name in the html did not exactly match the controller name in my app.js file, for instance:
index.html:
<script src="app.js"></script>
...
...
<body ng-app="flapperNews" ng-controller="MainCtrl">
app.js:
var app = angular.module('flapperNews', []);
app.controller('MyCtrl', ....
In the html, the controller name is "MainCtrl", and in the js I used the name "MyCtrl".
There is actually an error message embedded in the error url:
Error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=MainCtrl&p1=not%20a%20function%2C%20got%20undefined
Here it is without the hieroglyphics:
MainCtrl not a function got undefined
In other words, "There is no function named MainCtrl. Check your spelling."
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_
You can also use setShowSoftInputOnFocus(boolean) directly on API 21+ or through reflection on API 14+:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
editText.setShowSoftInputOnFocus(false);
} else {
try {
final Method method = EditText.class.getMethod(
"setShowSoftInputOnFocus"
, new Class[]{boolean.class});
method.setAccessible(true);
method.invoke(editText, false);
} catch (Exception e) {
// ignore
}
}
nil?
is a standard Ruby method that can be called on all objects and returns true
if the object is nil
:
b = nil
b.nil? # => true
empty?
is a standard Ruby method that can be called on some objects such as Strings, Arrays and Hashes and returns true
if these objects contain no element:
a = []
a.empty? # => true
b = ["2","4"]
b.empty? # => false
empty?
cannot be called on nil
objects.
blank?
is a Rails method that can be called on nil
objects as well as empty objects.
Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET
command. The first one to stop the service, the second one to start the service. Give them a STOP
and START
argument, followed by the service name.
In this example we restart the Printer Spooler service.
NET STOP "Print Spooler"
NET START "Print Spooler"
Note: unfortunately NET RESTART <service name>
does not exist.
changed = (evt) => {
this.isChecked = evt.target.checked;
}
<input type="checkbox" [checked]="checkbox" (change)="changed($event)" id="no"/>
Use
if (Build.VERSION.SDK_INT >= 19) {
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
It should solve the error.
You do not need to do it. In C (not C++) you were required to use enum Enumname to refer to a data element of the enumerated type. To simplify it you were allowed to typedef it to a single name data type.
typedef enum MyEnum {
//...
} MyEnum;
allowed functions taking a parameter of the enum to be defined as
void f( MyEnum x )
instead of the longer
void f( enum MyEnum x )
Note that the name of the typename does not need to be equal to the name of the enum. The same happens with structs.
In C++, on the other hand, it is not required, as enums, classes and structs can be accessed directly as types by their names.
// C++
enum MyEnum {
// ...
};
void f( MyEnum x ); // Correct C++, Error in C
Bootstrap 3
Try this. Simple solution with no dependencies.
$('[data-toggle="collapse"]').click(function() {
$('.collapse.in').collapse('hide')
});
_x000D_
You will have to use some sort of network sniffer if you want to get at this sort of data and you're likely to run into the same problem (pulling out the relevant data from the overall network traffic) with those that you do now with Wireshark.
You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.
The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.
With an appropriate predicate in hand, problem 1 simplifies to:
low_primes = {x for x in range(1, 100) if is_prime(x)}
And problem 2 simplifies to:
low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}
Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."
P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.
after your pc connects to other pc use these 4 step:
4 steps:
1- Edit this file: httpd.conf
for that click on wamp server and select Apache and select httpd.conf
2- Find this text: Deny from all
in the below tag:
<Directory "c:/wamp/www"><!-- maybe other url-->
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# AllowOverride FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
# Require all granted
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
</Directory>
3- Change to: Deny from none
like this:
<Directory "c:/wamp/www">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# AllowOverride FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
# Require all granted
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from none
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
4- Restart Apache
Don't forget restart Apache or all servises!!!
the shortest and simplest way is.
arrayHere = ['cat1', 'dog2', 'bat3'];
if(arrayHere[any key want to search])
console.log("yes found in array");
You may also try the Default encoding, which uses the current system's ANSI codepage.
StreamReader reader = new StreamReader(inputFilePath, Encoding.Default, true)
When you try using the Notepad "Save As" menu with the original file, look at the encoding combo box. It will tell you which encoding notepad guessed is used by the file.
Also, if it is an ANSI file, the detectEncodingFromByteOrderMarks parameter will probably not help much.
Can be achieved also with scriptrunner
ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30
Which also have some features as rollback , timeout and waiting.
POSIX SED:
$ - match last line
{ COMMANDS } - A group of commands may be enclosed between { and } characters. This is particularly useful when you want a group of commands to be triggered by a single address (or address-range) match.
Even simplier solution (still with [one line inline] javascript):
Use this as the body tag:
Note that body.
or this.
did not work for me. Only the long ; querySelector
allow the use of classList.remove
(Linux Chromium)
<body class="onload" onload="document.querySelector('body').classList.remove('onload')">
and add this line on top of your other css rules.
body.onload *{ transform: none !important; }
Take note that this can apply to opacity (as requested by OP [other posters] ) simply by using opacity as a transition trigger instead. (might even work on any other css ruling in the same fashion and you can use multiple class for explicity delay between triggering)
The logic is the same. Enforce no transform (with :none !important
on all child element of body.onload
and once the document is loaded remove the class to trigger all transition on all elements as specified in your css.
FIRST ANSWER BELOW (SEE EDIT ABOVE FOR SHORTER ANSWER)
Here is a reverse solution:
Works with multiple transition on multiple elements. Did not try cross-browser compatibility.
#rotated{
transform : rotate(90deg) /* any other transformation */;
transition 3s;
}
#translated{
transform : translate(90px) /* any other transformation */;
transition 3s;
}
.waitload{
transform: none !important;
}
<div id='rotated' class='waitload'>
rotate after load
</div>
<div id='translated' class='waitload'>
trasnlate after load
</div>
<script type="text/javascript">
// or body onload ?
[...document.querySelectorAll('.waitload')]
.map(e => e.classList.remove('waitload'));
</script>
I use this really simple small JavaScript library to validate a complete form in one single line of code:
jsFormValidator.App.create().Validator.applyRules('Login');
Check here: jsFormValidator
The benefit of this tool is that you just write a JSON object which describe your validation rules. There isn't any need to put in a line like:
<input type=text name="username" data-validate placeholder="Username">
data-validate
is injected in all the input fields of your form, but when using jsFormValidator, you don't require this heavy syntax and the validation will be applied to your form in one shot, without the need to touch your HTML code.
SQL
is a query language to operate on sets.
It is more or less standardized, and used by almost all relational database management systems: SQL Server, Oracle, MySQL, PostgreSQL, DB2, Informix, etc.
PL/SQL
is a proprietary procedural language used by Oracle
PL/pgSQL
is a procedural language used by PostgreSQL
TSQL
is a proprietary procedural language used by Microsoft in SQL Server.
Procedural languages are designed to extend SQL's abilities while being able to integrate well with SQL. Several features such as local variables and string/data processing are added. These features make the language Turing-complete.
They are also used to write stored procedures: pieces of code residing on the server to manage complex business rules that are hard or impossible to manage with pure set-based operations.
I would simply make the assignment happen in the ng-mouseover and ng-mouseleave; no need to bother js file :)
<ul ng-repeat="task in tasks">
<li ng-mouseover="hoverEdit = true" ng-mouseleave="hoverEdit = false">{{task.name}}</li>
<span ng-show="hoverEdit"><a>Edit</a></span>
</ul>
You can add as many headers as you like by calling addHeaderView() multiple times. You have to do it before setting the adapter to the list view.
And yes you can add header something like this way:
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.header, myListView, false);
myListView.addHeaderView(header, null, false);
That is the parent folder of bin which contains tomcat.exe file:
CATALINA_HOME='C:\Program Files\Apache Software Foundation\Tomcat 6.0'
CATALINA_BASE
is the same as CATALINA_HOME
.
With MySql 5.1 (Win7). To recreate DBs (InnoDbs) I've replaced all contents of following dirs (my.ini params):
datadir="C:/ProgramData/MySQL/MySQL Server 5.1/Data/"
innodb_data_home_dir="C:/MySQL Datafiles/"
After that I started MySql Service and all works fine.
While there does not appear to be a public, Facebook-curated list of error codes available, a number of folks have taken it upon themselves to publish lists of known codes.
Take a look at StackOverflow #4348018 - List of Facebook error codes for a number of useful resources.
Adam's answer is quite fast, but I found that random.getrandbits(1)
to be quite a lot faster. If you really want a boolean instead of a long then
bool(random.getrandbits(1))
is still about twice as fast as random.choice([True, False])
Both solutions need to import random
If utmost speed isn't to priority then random.choice
definitely reads better
$ python -m timeit -s "import random" "random.choice([True, False])"
1000000 loops, best of 3: 0.904 usec per loop
$ python -m timeit -s "import random" "random.choice((True, False))"
1000000 loops, best of 3: 0.846 usec per loop
$ python -m timeit -s "import random" "random.getrandbits(1)"
1000000 loops, best of 3: 0.286 usec per loop
$ python -m timeit -s "import random" "bool(random.getrandbits(1))"
1000000 loops, best of 3: 0.441 usec per loop
$ python -m timeit -s "import random" "not random.getrandbits(1)"
1000000 loops, best of 3: 0.308 usec per loop
$ python -m timeit -s "from random import getrandbits" "not getrandbits(1)"
1000000 loops, best of 3: 0.262 usec per loop # not takes about 20us of this
Added this one after seeing @Pavel's answer
$ python -m timeit -s "from random import random" "random() < 0.5"
10000000 loops, best of 3: 0.115 usec per loop
When Python parses a function, it notes when a variable assignment is made. When there is an assignment, it assumes by default that that variable is a local variable. To declare that the assignment refers to a global variable, you must use the global
declaration.
When you access a variable in a function, its value is looked up using the LEGB scoping rules.
So, the first example
x = 1
def inc():
x += 5
inc()
produces an UnboundLocalError
because Python determined x
inside inc
to be a local variable,
while accessing x
works in your second example
def inc():
print x
because here, in accordance with the LEGB rule, Python looks for x
in the local scope, does not find it, then looks for it in the extended scope, still does not find it, and finally looks for it in the global scope successfully.
Base on Francisco Daniel's answer I modified some of the Jquery code here's My version. I removed some excess code and use "fa" instead of "far" for the icon. I also remove the "far fa-minus-square" since I can't understand its purpose.
-- Edited --
I added the "draw" event for the button icon to update whenever the table is redrawn or reloaded. Because I noticed when I tried to reload the table using "myTable.ajax.reload()" the button icon is not changing.
https://codepen.io/john-kenneth-larbo/pen/zXeYpz
$(document).ready(function() {_x000D_
let myTable = $('#example').DataTable({_x000D_
columnDefs: [{_x000D_
orderable: false,_x000D_
className: 'select-checkbox',_x000D_
targets: 0,_x000D_
}],_x000D_
select: {_x000D_
style: 'os', // 'single', 'multi', 'os', 'multi+shift'_x000D_
selector: 'td:first-child',_x000D_
},_x000D_
order: [_x000D_
[1, 'asc'],_x000D_
],_x000D_
});_x000D_
_x000D_
myTable.on('select deselect draw', function () {_x000D_
var all = myTable.rows({ search: 'applied' }).count(); // get total count of rows_x000D_
var selectedRows = myTable.rows({ selected: true, search: 'applied' }).count(); // get total count of selected rows_x000D_
_x000D_
if (selectedRows < all) {_x000D_
$('#MyTableCheckAllButton i').attr('class', 'fa fa-square-o');_x000D_
} else {_x000D_
$('#MyTableCheckAllButton i').attr('class', 'fa fa-check-square-o');_x000D_
}_x000D_
_x000D_
});_x000D_
_x000D_
$('#MyTableCheckAllButton').click(function () {_x000D_
var all = myTable.rows({ search: 'applied' }).count(); // get total count of rows_x000D_
var selectedRows = myTable.rows({ selected: true, search: 'applied' }).count(); // get total count of selected rows_x000D_
_x000D_
_x000D_
if (selectedRows < all) {_x000D_
//Added search applied in case user wants the search items will be selected_x000D_
myTable.rows({ search: 'applied' }).deselect();_x000D_
myTable.rows({ search: 'applied' }).select();_x000D_
} else {_x000D_
myTable.rows({ search: 'applied' }).deselect();_x000D_
}_x000D_
});_x000D_
});
_x000D_
<table id="example" class="display" style="width:100%">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>_x000D_
<button style="border: none; background: transparent; font-size: 14px;" id="MyTableCheckAllButton">_x000D_
<i class="far fa-square"></i> _x000D_
</button>_x000D_
</th>_x000D_
<th>Name</th>_x000D_
<th>Position</th>_x000D_
<th>Office</th>_x000D_
<th>Age</th>_x000D_
<th>Salary</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Tiger Nixon</td>_x000D_
<td>System Architect</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>61</td>_x000D_
<td>$320,800</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Garrett Winters</td>_x000D_
<td>Accountant</td>_x000D_
<td>Tokyo</td>_x000D_
<td>63</td>_x000D_
<td>$170,750</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Ashton Cox</td>_x000D_
<td>Junior Technical Author</td>_x000D_
<td>San Francisco</td>_x000D_
<td>66</td>_x000D_
<td>$86,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Cedric Kelly</td>_x000D_
<td>Senior Javascript Developer</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>22</td>_x000D_
<td>$433,060</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Airi Satou</td>_x000D_
<td>Accountant</td>_x000D_
<td>Tokyo</td>_x000D_
<td>33</td>_x000D_
<td>$162,700</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Brielle Williamson</td>_x000D_
<td>Integration Specialist</td>_x000D_
<td>New York</td>_x000D_
<td>61</td>_x000D_
<td>$372,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Herrod Chandler</td>_x000D_
<td>Sales Assistant</td>_x000D_
<td>San Francisco</td>_x000D_
<td>59</td>_x000D_
<td>$137,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Rhona Davidson</td>_x000D_
<td>Integration Specialist</td>_x000D_
<td>Tokyo</td>_x000D_
<td>55</td>_x000D_
<td>$327,900</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Colleen Hurst</td>_x000D_
<td>Javascript Developer</td>_x000D_
<td>San Francisco</td>_x000D_
<td>39</td>_x000D_
<td>$205,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Sonya Frost</td>_x000D_
<td>Software Engineer</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>23</td>_x000D_
<td>$103,600</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Jena Gaines</td>_x000D_
<td>Office Manager</td>_x000D_
<td>London</td>_x000D_
<td>30</td>_x000D_
<td>$90,560</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
<tfoot>_x000D_
<tr>_x000D_
<th></th>_x000D_
<th>Name</th>_x000D_
<th>Position</th>_x000D_
<th>Office</th>_x000D_
<th>Age</th>_x000D_
<th>Salary</th>_x000D_
</tr>_x000D_
</tfoot>_x000D_
</table>
_x000D_
If you want a distiction for this case I would recommend to use a matrix
instead, where:
matrix([1,2,3]) == matrix([1,2,3]).transpose()
gives:
matrix([[ True, False, False],
[False, True, False],
[False, False, True]], dtype=bool)
You can also use a ndarray
explicitly adding a second dimension:
array([1,2,3])[None,:]
#array([[1, 2, 3]])
and:
array([1,2,3])[:,None]
#array([[1],
# [2],
# [3]])
Note that you need to consider whether you want methods from base classes which are inherited (but not overridden) included in the result. The dir()
and inspect.getmembers()
operations do include base class methods, but use of the __dict__
attribute does not.
That's not possible. localhost
always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.
If you want to access it e.g. in a browser, connect to it using the local IP instead:
http://192.168.180.1:8000
This is just an example of course, you can find out the actual IP by issuing an ifconfig
command on a shell in the guest operating system.
An rvalue reference is a type that behaves much like the ordinary reference X&, with several exceptions. The most important one is that when it comes to function overload resolution, lvalues prefer old-style lvalue references, whereas rvalues prefer the new rvalue references:
void foo(X& x); // lvalue reference overload
void foo(X&& x); // rvalue reference overload
X x;
X foobar();
foo(x); // argument is lvalue: calls foo(X&)
foo(foobar()); // argument is rvalue: calls foo(X&&)
So what is an rvalue? Anything that is not an lvalue. An lvalue being an expression that refers to a memory location and allows us to take the address of that memory location via the & operator.
It is almost easier to understand first what rvalues accomplish with an example:
#include <cstring>
class Sample {
int *ptr; // large block of memory
int size;
public:
Sample(int sz=0) : ptr{sz != 0 ? new int[sz] : nullptr}, size{sz}
{
if (ptr != nullptr) memset(ptr, 0, sz);
}
// copy constructor that takes lvalue
Sample(const Sample& s) : ptr{s.size != 0 ? new int[s.size] :\
nullptr}, size{s.size}
{
if (ptr != nullptr) memcpy(ptr, s.ptr, s.size);
std::cout << "copy constructor called on lvalue\n";
}
// move constructor that take rvalue
Sample(Sample&& s)
{ // steal s's resources
ptr = s.ptr;
size = s.size;
s.ptr = nullptr; // destructive write
s.size = 0;
cout << "Move constructor called on rvalue." << std::endl;
}
// normal copy assignment operator taking lvalue
Sample& operator=(const Sample& s)
{
if(this != &s) {
delete [] ptr; // free current pointer
size = s.size;
if (size != 0) {
ptr = new int[s.size];
memcpy(ptr, s.ptr, s.size);
} else
ptr = nullptr;
}
cout << "Copy Assignment called on lvalue." << std::endl;
return *this;
}
// overloaded move assignment operator taking rvalue
Sample& operator=(Sample&& lhs)
{
if(this != &s) {
delete [] ptr; //don't let ptr be orphaned
ptr = lhs.ptr; //but now "steal" lhs, don't clone it.
size = lhs.size;
lhs.ptr = nullptr; // lhs's new "stolen" state
lhs.size = 0;
}
cout << "Move Assignment called on rvalue" << std::endl;
return *this;
}
//...snip
};
The constructor and assignment operators have been overloaded with versions that take rvalue references. Rvalue references allow a function to branch at compile time (via overload resolution) on the condition "Am I being called on an lvalue or an rvalue?". This allowed us to create more efficient constructor and assignment operators above that move resources rather copy them.
The compiler automatically branches at compile time (depending on the whether it is being invoked for an lvalue or an rvalue) choosing whether the move constructor or move assignment operator should be called.
Summing up: rvalue references allow move semantics (and perfect forwarding, discussed in the article link below).
One practical easy-to-understand example is the class template std::unique_ptr. Since a unique_ptr maintains exclusive ownership of its underlying raw pointer, unique_ptr's can't be copied. That would violate their invariant of exclusive ownership. So they do not have copy constructors. But they do have move constructors:
template<class T> class unique_ptr {
//...snip
unique_ptr(unique_ptr&& __u) noexcept; // move constructor
};
std::unique_ptr<int[] pt1{new int[10]};
std::unique_ptr<int[]> ptr2{ptr1};// compile error: no copy ctor.
// So we must first cast ptr1 to an rvalue
std::unique_ptr<int[]> ptr2{std::move(ptr1)};
std::unique_ptr<int[]> TakeOwnershipAndAlter(std::unique_ptr<int[]> param,\
int size)
{
for (auto i = 0; i < size; ++i) {
param[i] += 10;
}
return param; // implicitly calls unique_ptr(unique_ptr&&)
}
// Now use function
unique_ptr<int[]> ptr{new int[10]};
// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(\
static_cast<unique_ptr<int[]>&&>(ptr), 10);
cout << "output:\n";
for(auto i = 0; i< 10; ++i) {
cout << new_owner[i] << ", ";
}
output:
10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
static_cast<unique_ptr<int[]>&&>(ptr)
is usually done using std::move
// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(std::move(ptr),0);
An excellent article explaining all this and more (like how rvalues allow perfect forwarding and what that means) with lots of good examples is Thomas Becker's C++ Rvalue References Explained. This post relied heavily on his article.
A shorter introduction is A Brief Introduction to Rvalue References by Stroutrup, et. al
Here is the Java Implementation of this approach:
public static int countAllFactors(int num)
{
TreeSet<Integer> tree_set = new TreeSet<Integer>();
for (int i = 1; i * i <= num; i+=1)
{
if (num % i == 0)
{
tree_set.add(i);
tree_set.add(num / i);
}
}
System.out.print(tree_set);
return tree_set.size();
}
The path to the SDK is:
C:\Users\USERNAME\AppData\Local\Android\sdk
This can be used in Eclipse after you replace USERNAME with your Windows user name.
Use the system_profiler | grep "Cores"
command.
I have a:
MacBook Pro Retina, Mid 2012.
Processor: 2.6 GHz Intel Core i7
user$ system_profiler | grep "Cores"
Total Number of Cores: 4
user$ sysctl -n hw.ncpu
8
According to Wikipedia, (http://en.wikipedia.org/wiki/Intel_Core#Core_i7) there is no Core i7 with 8 physical cores so the Hyperthreading idea must be the case. Ignore sysctl
and use the system_profiler
value for accuracy. The real question is whether or not you can efficiently run applications with 4 cores (long compile jobs?) without interrupting other processes.
Running a compiler parallelized with 4 cores doesn't appear to dramatically affect regular OS operations. So perhaps treating it as 8 cores is not so bad.
Just an idea:
You may get the filesize by running command "dir":
>dir thing
Then again it returns so many things.
Maybe you can get it from there if you look for it.
But I am not sure.
This should work.
string temp = mystring.Replace("\n", "");
Are you sure there are actual \n new lines in your original string?
If you're converting anything other than simple types like integers or booleans, you'd need to write your own function/method for the type that you're trying to convert, otherwise PHP will just print the type (such as array, GoogleSniffer, or Bidet).
Your curl gets timed out. Probably the url you are trying that requires more that 30 seconds.
If you are running the script through browser, then set the set_time_limit
to zero for infinite seconds.
set_time_limit(0);
Increase the curl's operation time limit using this option CURLOPT_TIMEOUT
curl_setopt($ch, CURLOPT_TIMEOUT,500); // 500 seconds
It can also happen for infinite redirection from the server. To halt this try to run the script with follow location disabled.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
@($output).Count
does not always produce correct results.
I used the ($output | Measure).Count
method.
I found this with VMware Get-VmQuestion cmdlet:
$output = Get-VmQuestion -VM vm1
@($output).Count
The answer it gave is one, whereas
$output
produced no output (the correct answer was 0 as produced with the Measure
method).
This only seemed to be the case with 0 and 1. Anything above 1 was correct with limited testing.
A Simple approach to change the Font Size in Visual Studio Work Environment :
Go To : File -> Preferences -> Settings OR Press CTRL+, i.e. CTRL + COMMA.
This will open settings.json.
You can see 3 tabs there :
Go to User Settings and Add this :
{
"editor.fontSize": 16
}
Now just save and close the file.
In above code, 16 represents the font size. Increase of Decrease as per your wish.
If you are optimizing your page for IE8 or newer, you should really consider whether you need jquery or not. Modern browsers have many assets natively which jquery provides.
If you care for performance, you can have incredible performance benefits (2-10 faster) using native javascript: http://jsperf.com/jquery-vs-native-selector-and-element-style/2
I transformed a div-tagcloud from jquery to native javascript (IE8+ compatible), the results are impressive. 4 times faster with just a little overhead.
Number of lines Execution Time
Jquery version : 340 155ms
Native version : 370 27ms
You Might Not Need Jquery provides a really nice overview, which native methods replace for which browser version.
http://youmightnotneedjquery.com/
Appendix: Further speed comparisons how native methods compete to jquery
Go to your program.cs file add UseUrs method to set your url, make sure you don't use a reserved url or port
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
// params string[] urls
.UseUrls(urls: "http://localhost:10000")
.Build();
}
// you need to have a list of data that you want the spinner to display
List<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);
also to find out what is selected you could do something like this
String selected = sItems.getSelectedItem().toString();
if (selected.equals("what ever the option was")) {
}
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
//if you want to interrupt going to another location.
event.preventDefault(); });
For anyone trying to achieve this with Python 3.3+, the Windows installer now includes an option to add python.exe to the system search path. Read more in the docs.
test = {'foo': 'bar', 'hello': 'world'}
ls = []
for key in test.keys():
ls.append(key)
print(ls[0])
Conventional way of appending the keys to a statically defined list and then indexing it for same
In some cases it is tied to how the field is used. In some DB engines the field differences determine how (and if) you search for text in the field. CharFields are typically used for things that are searchable, like if you want to search for "one" in the string "one plus two". Since the strings are shorter they are less time consuming for the engine to search through. TextFields are typically not meant to be searched through (like maybe the body of a blog) but are meant to hold large chunks of text. Now most of this depends on the DB Engine and like in Postgres it does not matter.
Even if it does not matter, if you use ModelForms you get a different type of editing field in the form. The ModelForm will generate an HTML form the size of one line of text for a CharField and multiline for a TextField.
this is more likely happening because somewhere along your certificate chain you have a certificate, more likely an old root, which is still signed with the MD2RSA algorythm.
You need to locate it into your certificate store and delete it.
Then get back to your certification authority and ask them for then new root.
It will more likely be the same root with the same validity period but it has been recertified with SHA1RSA.
Hope this help.
Using one of the above solutions ( @mickmackusa ), I made a working prototype in React 16.8+ using Hooks.
https://codesandbox.io/s/heuristic-dewdney-0h2y2
I hope it helps someone.
The difference is, re.match()
misleads anyone accustomed to Perl, grep, or sed regular expression matching, and re.search()
does not. :-)
More soberly, As John D. Cook remarks, re.match()
"behaves as if every pattern has ^ prepended." In other words, re.match('pattern')
equals re.search('^pattern')
. So it anchors a pattern's left side. But it also doesn't anchor a pattern's right side: that still requires a terminating $
.
Frankly given the above, I think re.match()
should be deprecated. I would be interested to know reasons it should be retained.
You can try doing
<p>
<a href="MY WEBSITE LINK" target="_blank">
<img src="IMAGE LINK" style='width:100%;' border="0" alt="Null">
</a>
</p>
This should scale your image if in a fluid layout.
For responsive (meaning your layout reacts to the size of the window) you can add a class to the image and use @media
queries in CSS to change the width of the image.
Note that changing the height of the image will mess with the ratio.
Would not that have to be:
.replaceAll("\"","\\\\\"")
FIVE backslashes in the replacement String.
instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0;
once your window has scrolled pass a certain height:
jQuery
$(window).scroll(function(){
if ($(this).scrollTop() > 135) {
$('#task_flyout').addClass('fixed');
} else {
$('#task_flyout').removeClass('fixed');
}
});
css
.fixed {position:fixed; top:0; left:0;}
I kept having this problem whenever I tried to start an app pool more than once. Rather than rebooting, I simply run the Application Information Service. (Note: This service is set to run manually on my system, which may be the reason for the problem.) From its description, it seems obvious that it is somehow involved:
Facilitates the running of interactive applications with additional administrative privileges. If this service is stopped, users will be unable to launch applications with the additional administrative privileges they may require to perform desired user tasks.
Presumably, IIS manager (as well as most other processes running as an administrator) does not maintain admin privileges throughout the life of the process, but instead request admin rights from the Application Information service on a case-by-case basis.
Source: social.technech.microsoft.com