I could resolve this problem by updating macOS and XCode.
Why cant I do this:
List<Object> object = new List<Object>();
You can't do this because List
is an interface, and interfaces cannot be instantiated. Only (concrete) classes can be. Examples of concrete classes implementing List
include ArrayList
, LinkedList
etc.
Here is how one would create an instance of ArrayList
:
List<Object> object = new ArrayList<Object>();
I have a method that returns a
List<?>
, how would I turn that into aList<Object>
Show us the relevant code and I'll update the answer.
No, but since C++11 there is [u]int8_t.
Type hint are a recent addition to a dynamic language where for decades folks swore naming conventions as simple as Hungarian (object label with first letter b = Boolean, c = character, d = dictionary, i = integer, l = list, n = numeric, s = string, t= tuple) were not needed, too cumbersome, but now have decided that, oh wait ... it is way too much trouble to use the language (type()) to recognize objects, and our fancy IDEs need help doing anything that complicated, and that dynamically assigned object values make them completely useless anyhow, whereas a simple naming convention could have resolved all of it, for any developer, at a mere glance.
There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.
Here is an example using Posh-SSH:
# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)
# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'
# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'
# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH
# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential
# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath
#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }
# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath
Some additional notes:
That should give you a decent starting point.
You can also use:
@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")
To specify the format of your output in a scenario where you need to use Charset, Type, etc.
Inspired by anubhava's answer, which I think is not actually acceptable as it runs each command twice.
save_output() {
exec 1>&3
{ [ -f /tmp/current ] && mv /tmp/current /tmp/last; }
exec > >(tee /tmp/current)
}
exec 3>&1
trap save_output DEBUG
This way the output of last command is in /tmp/last and the command is not called twice.
You can change the value of the referrer in the HTTP header using the Web Request API.
It requires a background js script for it's use. You can use the onBeforeSendHeaders as it modifies the header before the request is sent.
Your code will be something like this :
chrome.webRequest.onBeforeSendHeaders.addEventListener(function(details){
var newRef = "http://new-referer/path";
var hasRef = false;
for(var n in details.requestHeaders){
hasRef = details.requestHeaders[n].name == "Referer";
if(hasRef){
details.requestHeaders[n].value = newRef;
break;
}
}
if(!hasRef){
details.requestHeaders.push({name:"Referer",value:newRef});
}
return {requestHeaders:details.requestHeaders};
},
{
urls:["http://target/*"]
},
[
"requestHeaders",
"blocking"
]);
urls : It acts as a request filter, and invokes the listener only for certain requests.
For more info: https://developer.chrome.com/extensions/webRequest
I like to use a global "app", rather than exporting a function etc
one way: List.AddRange() depending on the types?
// the index of each item in fieldNames must correspond to
// the correct index in resultItems
var fieldnames = new []{"itemtype", "etc etc "};
for (int e = 0; e < fieldNames.Length - 1; e++)
{
newRecord
.GetType()
.GetProperty(fieldNames[e])
.SetValue(newRecord, resultItems[e]);
}
To get the raw post body regardless of the content type, use request.get_data()
. If you use request.data
, it calls request.get_data(parse_form_data=True)
, which will populate the request.form
MultiDict
and leave data
empty.
The answers did help, but I think a full implementation of this will help a lot of people.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Dom
{
class Dom
{
public static string make_Sting_From_Dom(string reportname)
{
try
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
// Retrieve resource as a stream
Stream data = client.OpenRead(new Uri(reportname.Trim()));
// Retrieve the text
StreamReader reader = new StreamReader(data);
string htmlContent = reader.ReadToEnd();
string mtch = "TILDE";
bool b = htmlContent.Contains(mtch);
if (b)
{
int index = htmlContent.IndexOf(mtch);
if (index >= 0)
Console.WriteLine("'{0} begins at character position {1}",
mtch, index + 1);
}
// Cleanup
data.Close();
reader.Close();
return htmlContent;
}
catch (Exception)
{
throw;
}
}
static void Main(string[] args)
{
make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
}
}
}
Keeping in mind the points made in @John Woo's comment/link above, this is how I typically would handle it:
SELECT t1.ID, t1.Name
FROM Table1 t1
WHERE NOT EXISTS (
SELECT TOP 1 NULL
FROM Table2 t2
WHERE t1.ID = t2.ID
)
Put the tab name on the page header or group TableRow1 in your report so that it will appear in the "A1" position on each Excel sheet. Then run this macro in your Excel workbook.
Sub SelectSheet()
For i = 1 To ThisWorkbook.Sheets.Count
mysheet = "Sheet" & i
On Error GoTo 10
Sheets(mysheet).Select
Set Target = Range("A1")
If Target = "" Then Exit Sub
On Error GoTo Badname
ActiveSheet.Name = Left(Target, 31)
GoTo 10
Badname:
MsgBox "Please revise the entry in A1." & Chr(13) _
& "It appears to contain one or more " & Chr(13) _
& "illegal characters." & Chr(13)
Range("A1").Activate
10
Next i
End Sub
No need to apologize for asking a question! Try using the RIGHT
function. It returns the last n characters of a string.
=RIGHT(A1, 1)
In more complicated build scenarios, it is common to break compilation into stages, with compilation and assembly happening first (output to object files), and linking object files into a final executable or library afterward--this prevents having to recompile all object files when their source files haven't changed. That's why including the linking flag -lm
isn't working when you put it in CFLAGS
(CFLAGS
is used in the compilation stage).
The convention for libraries to be linked is to place them in either LOADLIBES
or LDLIBS
(GNU make includes both, but your mileage may vary):
LDLIBS=-lm
This should allow you to continue using the built-in rules rather than having to write your own linking rule. For other makes, there should be a flag to output built-in rules (for GNU make, this is -p
). If your version of make does not have a built-in rule for linking (or if it does not have a placeholder for -l
directives), you'll need to write your own:
client.o: client.c
$(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c -o $@ $<
client: client.o
$(CC) $(LDFLAGS) $(TARGET_ARCH) $^ $(LOADLIBES) $(LDLIBS) -o $@
It might be the JavaScript check for some valid condition.
Two things you can perform a/c to your requirements:
String barcode="0000000047166";
WebElement strLocator = driver.findElement(By.xpath("//*[@id='div-barcode']"));
strLocator.sendKeys(barcode);
If you are trying to trigger an event on the anchor, then the code you have will work.
$(document).ready(function() {
$('a#titleee').trigger('click');
});
OR
$(document).ready(function() {
$('#titleee li a[href="#inline"]').click();
});
OR
$(document).ready(function() {
$('ul#titleee li a[href="#inline"]').click();
});
When you want to create interval store promise to variable:
var p = $interval(function() { ... },1000);
And when you want to stop / clear the interval simply use:
$interval.cancel(p);
Here is example of taking XML file from raw folder:
InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML
Then you can:
String sxml = readTextFile(XmlFileInputStream);
when:
public String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
It seems ridiculous that you can't set/reset an identity column with a single command to cover both cases of whether or not the table has had records inserted. I couldn't understand the behavior I was experiencing until I stumbled across this question on SO!
My solution (ugly but works) is to explicitly check the sys.identity_columns.last_value
table (which tells you whether or not the table has had records inserted) and call the appropriate DBCC CHECKIDENT
command in each case. It is as follows:
DECLARE @last_value INT = CONVERT(INT, (SELECT last_value FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'MyTable'));
IF @last_value IS NULL
BEGIN
-- Table newly created and no rows inserted yet; start the IDs off from 1
DBCC CHECKIDENT ('MyTable', RESEED, 1);
END
ELSE
BEGIN
-- Table has rows; ensure the IDs continue from the last ID used
DECLARE @lastValUsed INT = (SELECT ISNULL(MAX(ID),0) FROM MyTable);
DBCC CHECKIDENT ('MyTable', RESEED, @lastValUsed);
END
The most simple and straightforward C/C++ implementation that I found is in a link at the bottom of this page:
Web Page: http://www.barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code
Code Download Link: https://barrgroup.com/code/crc.zip
It is a simple standalone implementation with one .h and one .c file. There is support for CRC32, CRC16 and CRC_CCITT thru the use of a define. Also, the code lets the user change parameter settings like the CRC polynomial, initial/final XOR value, and reflection options if you so desire.
The license is not explicitly defined ala LGPL or similar. However the site does say that they are placing the code in the public domain for any use. The actual code files also say this.
Hope it helps!
As of PHP 7.1,
catch( AError | BError $e )
{
handler1( $e )
}
interestingly, you can also:
catch( AError | BError $e )
{
handler1( $e )
} catch (CError $e){
handler2($e);
} catch(Exception $e){
handler3($e);
}
and in earlier versions of PHP:
catch(Exception $ex){
if($ex instanceof AError){
//handle a AError
} elseif($ex instanceof BError){
//handle a BError
} else {
throw $ex;//an unknown exception occured, throw it further
}
}
You can use this code for toggle your element var ele = jQuery("yourelementid"); ele.slideToggle('slow'); this will work for you :)
In most use-cases, using a StringBuilder
(as already answered) is a good way to do this. However, if performance matters, this may be a good alternative.
/**
* Insert the 'insert' String at the index 'position' into the 'target' String.
*
* ````
* insertAt("AC", 0, "") -> "AC"
* insertAt("AC", 1, "xxx") -> "AxxxC"
* insertAt("AB", 2, "C") -> "ABC
* ````
*/
public static String insertAt(final String target, final int position, final String insert) {
final int targetLen = target.length();
if (position < 0 || position > targetLen) {
throw new IllegalArgumentException("position=" + position);
}
if (insert.isEmpty()) {
return target;
}
if (position == 0) {
return insert.concat(target);
} else if (position == targetLen) {
return target.concat(insert);
}
final int insertLen = insert.length();
final char[] buffer = new char[targetLen + insertLen];
target.getChars(0, position, buffer, 0);
insert.getChars(0, insertLen, buffer, position);
target.getChars(position, targetLen, buffer, position + insertLen);
return new String(buffer);
}
Look into the Thinktecture IdentityModel library -- it has full CORS support:
http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/
And it can dynamically emit the ACA-Origin you want.
The Right way is to define ItemDecoration
for the RecyclerView
is as following
SimpleDividerItemDecoration.java
public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable mDivider;
public SimpleDividerItemDecoration(Context context) {
mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider);
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
line_divider.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="1dp"
android:height="1dp" />
<solid android:color="@color/dark_gray" />
</shape>
Finally set it like this
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));
As pointed by @Alan Solitar
context.getResources().getDrawable(R.drawable.line_divider);
is depreciated instead of that you can use
ContextCompat.getDrawable(context,R.drawable.line_divider);
Since Android 4.2 (API 17) nested fragments become available http://developer.android.com/about/versions/android-4.2.html#NestedFragments
To place fragment inside other fragment use getChildFragmentManager()
It also available in support library!
I found that I can run this command:
notepad $((Split-Path $profile -Parent) + "\profile.ps1")
and it opens my default powershell profile (at least when using Terminal for Windows). I found that here.
Then add an alias. For example, here is my alias of jn
for jupyter notebook
(I hate typing out the cumbersome jupyter notebook
every time):
Set-Alias -Name jn -Value C:\Users\words\Anaconda3\Scripts\jupyter-notebook.exe
Open Command prompt or terminal and use below syntax
pip install --upgrade [package]==[specific version or latest version]
For Example
pip install --upgrade numpy==1.19.1
Try this:
retVal = Shell("python.exe <full path to your python script>", vbNormalFocus)
replace <full path to your python script>
with the full path
This is a good case for using another thread:
// Call some method
this.Method();
Task.Factory.StartNew(() =>
{
Thread.Sleep(20000);
// Do things here.
// NOTE: You may need to invoke this to your main thread depending on what you're doing
});
The above code expects .NET 4.0 or above, otherwise try:
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
{
Thread.Sleep(20000);
// Do things here
}));
This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates
which is more suitable than distinct
for certain queries.
Suppose you have this DataFrame:
+-------+-------------+
|country| continent|
+-------+-------------+
| china| asia|
| brazil|south america|
| france| europe|
| china| asia|
+-------+-------------+
Here's how to take all the distinct countries and run a transformation:
df
.select("country")
.distinct
.withColumn("country", concat(col("country"), lit(" is fun!")))
.show()
+--------------+
| country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+
You can use dropDuplicates
instead of distinct
if you don't want to lose the continent
information:
df
.dropDuplicates("country")
.withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
.show(false)
+-------+-------------+------------------------------------+
|country|continent |description |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe |france is a country in europe |
|china |asia |china is a country in asia |
+-------+-------------+------------------------------------+
See here for more information about filtering DataFrames and here for more information on dropping duplicates.
Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.
Swift 5
I used "actionsheet" style for iPhone and "alert" for iPad. iPad displays in the center of the screen. No need to specify sourceView or anchor the view anywhere.
var alertStyle = UIAlertController.Style.actionSheet
if (UIDevice.current.userInterfaceIdiom == .pad) {
alertStyle = UIAlertController.Style.alert
}
let alertController = UIAlertController(title: "Your title", message: nil, preferredStyle: alertStyle)
Edit: Per ShareToD's suggestion, updated deprecated "UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad" check
The nohup command is a signal masking utility and catches the hangup signal. Where as ampersand doesn’t catch the hang up signals. The shell will terminate the sub command with the hang up signal when running a command using & and exiting the shell. This can be prevented by using nohup, as it catches the signal. Nohup command accept hang up signal which can be sent to a process by the kernel and block them. Nohup command is helpful in when a user wants to start long running application log out or close the window in which the process was initiated. Either of these actions normally prompts the kernel to hang up on the application, but a nohup wrapper will allow the process to continue. Using the ampersand will run the command in a child process and this child of the current bash session. When you exit the session, all of the child processes of that process will be killed. The ampersand relates to job control for the active shell. This is useful for running a process in a session in the background.
SilverSkin and Anders are both correct. You can use parentheses to execute multiple commands. However, you have to make sure that the commands themselves (and their parameters) do not contain parentheses. cmd
greedily searches for the first closing parenthesis, instead of handling nested sets of parentheses gracefully. This may cause the rest of the command line to fail to parse, or it may cause some of the parentheses to get passed to the commands (e.g. DEL myfile.txt)
).
A workaround for this is to split the body of the loop into a separate function. Note that you probably need to jump around the function body to avoid "falling through" into it.
FOR /r %%X IN (*.txt) DO CALL :loopbody %%X
REM Don't "fall through" to :loopbody.
GOTO :EOF
:loopbody
ECHO %1
DEL %1
GOTO :EOF
High performance ANPR Library - http://www.dtksoft.com/dtkanpr.php. This is commercial, but they provide trial key.
Based on Daniel's answer, I think I've got something that works:
^(.(?!test))*$
The key is that you need to make the negative assertion on every character in the string
Take a look at the Dictionary class in System::Collections::Generic.
Dictionary<myComplex, int> myMap = new Dictionary<myComplex, int>();
I was going to answer this question. Then I saw it get marked as a duplicate of this question, after I'd written the code, so I am going to post my solution here.
Keeping in mind that you have to re-write the text file. First I read the entire file, and store it in a string. Then I store each line as a index of a string array, ex line one = array index 0. I then edit the index corresponding to the line that you wish to edit. Once this is done I concatenate all the strings in the array into a single string. Then I write the new string into the file, which writes over the old content. Don't worry about losing your old content as it has been written again with the edit. below is the code I used.
public class App {
public static void main(String[] args) {
String file = "file.txt";
String newLineContent = "Hello my name is bob";
int lineToBeEdited = 3;
ChangeLineInFile changeFile = new ChangeLineInFile();
changeFile.changeALineInATextFile(file, newLineContent, lineToBeEdited);
}
}
And the class.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
public class ChangeLineInFile {
public void changeALineInATextFile(String fileName, String newLine, int lineNumber) {
String content = new String();
String editedContent = new String();
content = readFile(fileName);
editedContent = editLineInContent(content, newLine, lineNumber);
writeToFile(fileName, editedContent);
}
private static int numberOfLinesInFile(String content) {
int numberOfLines = 0;
int index = 0;
int lastIndex = 0;
lastIndex = content.length() - 1;
while (true) {
if (content.charAt(index) == '\n') {
numberOfLines++;
}
if (index == lastIndex) {
numberOfLines = numberOfLines + 1;
break;
}
index++;
}
return numberOfLines;
}
private static String[] turnFileIntoArrayOfStrings(String content, int lines) {
String[] array = new String[lines];
int index = 0;
int tempInt = 0;
int startIndext = 0;
int lastIndex = content.length() - 1;
while (true) {
if (content.charAt(index) == '\n') {
tempInt++;
String temp2 = new String();
for (int i = 0; i < index - startIndext; i++) {
temp2 += content.charAt(startIndext + i);
}
startIndext = index;
array[tempInt - 1] = temp2;
}
if (index == lastIndex) {
tempInt++;
String temp2 = new String();
for (int i = 0; i < index - startIndext + 1; i++) {
temp2 += content.charAt(startIndext + i);
}
array[tempInt - 1] = temp2;
break;
}
index++;
}
return array;
}
private static String editLineInContent(String content, String newLine, int line) {
int lineNumber = 0;
lineNumber = numberOfLinesInFile(content);
String[] lines = new String[lineNumber];
lines = turnFileIntoArrayOfStrings(content, lineNumber);
if (line != 1) {
lines[line - 1] = "\n" + newLine;
} else {
lines[line - 1] = newLine;
}
content = new String();
for (int i = 0; i < lineNumber; i++) {
content += lines[i];
}
return content;
}
private static void writeToFile(String file, String content) {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))) {
writer.write(content);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String readFile(String filename) {
String content = null;
File file = new File(filename);
FileReader reader = null;
try {
reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return content;
}
}
This is working for me (i use laravel 5.6).
$collection = MyModel::all()->groupBy('column');
If you want to convert the collection to plain php array, you can use toArray()
$array = MyModel::all()->groupBy('column')->toArray();
Since other SO answers link to this question it's worth noting that there is another option now in PyOxidizer.
It's a rust utility which works in some of the same ways as pyinstaller, however has some additional features detailed here, to summarize the key ones:
onefile
mode(One other advantage of pyoxidizer
is that it does not seem to suffer from the GLIBC_X.XX not found
problem that can crop up with pyinstaller if you've created your binary on a system that has a glibc version newer than the target system).
Overall pyinstaller is much simpler to use than PyOxidizer, which often requires some complexity in the configuration file, and it's less Pythony since it's written in Rust and uses a configuration file format not very familiar in the Python world, but PyOxidizer does some more advanced stuff, especially if you are looking to produce single binaries (which is not pyinstaller's default).
You could do a simple calculation, pimped with an regex, if the chosen date format is 'YYYYMM':
echo $(($(date +"%Y%m") - 1)) | sed -e 's/99$/12/'
In January of 2020 it will return 201912 ;-) But, it's only a workaround, when date does not have calculation options and other dateinterpreter options (e.g. using perl) not available ;-)
In some scenarios {new: true}
is not working.
Then you can try this.
{'returnNewDocument':true}
Using constants allows to combine multiple fields for verification:
class LoginFrm extends React.Component {_x000D_
constructor() {_x000D_
super();_x000D_
this.state = {_x000D_
email: '',_x000D_
password: '',_x000D_
};_x000D_
}_x000D_
_x000D_
handleEmailChange = (evt) => {_x000D_
this.setState({ email: evt.target.value });_x000D_
}_x000D_
_x000D_
handlePasswordChange = (evt) => {_x000D_
this.setState({ password: evt.target.value });_x000D_
}_x000D_
_x000D_
handleSubmit = () => {_x000D_
const { email, password } = this.state;_x000D_
alert(`Welcome ${email} password: ${password}`);_x000D_
}_x000D_
_x000D_
render() {_x000D_
const { email, password } = this.state;_x000D_
const enabled =_x000D_
email.length > 0 &&_x000D_
password.length > 0;_x000D_
return (_x000D_
<form onSubmit={this.handleSubmit}>_x000D_
<input_x000D_
type="text"_x000D_
placeholder="Email"_x000D_
value={this.state.email}_x000D_
onChange={this.handleEmailChange}_x000D_
/>_x000D_
_x000D_
<input_x000D_
type="password"_x000D_
placeholder="Password"_x000D_
value={this.state.password}_x000D_
onChange={this.handlePasswordChange}_x000D_
/>_x000D_
<button disabled={!enabled}>Login</button>_x000D_
</form>_x000D_
)_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<LoginFrm />, document.body);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<body>_x000D_
_x000D_
_x000D_
</body>
_x000D_
you can use arraylist object from collections class
using System.Collections;
static void Main()
{
ArrayList arr = new ArrayList();
}
when you want to add elements you can use
arr.Add();
Similar Issue
I have an interface that looked roughly like:
Task DoSomething(int arg);
Symptoms
My unit test failed when my service under test awaited
the call to DoSomething
.
Fix
Unlike the accepted answer, you are unable to call .ReturnsAsync()
on your Setup()
of this method in this scenario, because the method returns the non-generic Task
, rather than Task<T>
.
However, you are still able to use .Returns(Task.FromResult(default(object)))
on the setup, allowing the test to pass.
I know you asked for non-looping solutions, but the only solutions I can come up with probably loop internally anyway:
map(int,y)
or:
[i*1 for i in y]
or:
import numpy
y=numpy.array(y)
y*1
What worked for me was:
<div style='display: inline-flex; width: 80px; height: 80px;'>
<img style='max-width: 100%; max-height: 100%' src='image file'>
</div>
inline-flex was required to keep the images from going outside of the div.
If this android:divider="@null"
doesn't work, maybe changing your ListViews for Recycler Views?
There are two very different types of pages in SharePoint: Application Pages and Site Pages.
If you are going to use your page as an Application Page, you can safely use inline code or code behind in your page, as Application pages live on the file system.
If it's going to be a Site page, you can safely write inline code as long as you have it like that in the initial deployment. However if your site page is going to be customized at some point in the future, the inline code will no longer work because customized site pages live in the database and are executed in asp.net's "no compile" mode.
Bottom line is - you can write aspx pages with inline code. The only problem is with customized Site pages... which will no longer care for your inline code.
Thanks Notable1, works for me with the tidytextr Create a dataframe with the name of files in one column and content in other.
diretorio <- "D:/base"
arquivos <- list.files(diretorio, pattern = "*.PDF")
quantidade <- length(arquivos)
#
df = NULL
for (k in 1:quantidade) {
nome = arquivos[k]
print(nome)
Sys.sleep(1)
dados = read_pdf(arquivos[k],ocr = T)
print(dados)
Sys.sleep(1)
df = rbind(df, data.frame(nome,dados))
Sys.sleep(1)
}
Encoding(df$text) <- "UTF-8"
New in version 3.4.
import pathlib
print(pathlib.Path('yourPath.example').suffix) # '.example'
I'm surprised no one has mentioned pathlib
yet, pathlib
IS awesome!
If you need all the suffixes (eg if you have a .tar.gz
), .suffixes
will return a list of them!
Good evening,
I prefer to just have a simple extension method:
Date.prototype.startOfWeek = function (pStartOfWeek) {
var mDifference = this.getDay() - pStartOfWeek;
if (mDifference < 0) {
mDifference += 7;
}
return new Date(this.addDays(mDifference * -1));
}
You'll notice this actually utilizes another extension method that I use:
Date.prototype.addDays = function (pDays) {
var mDate = new Date(this.valueOf());
mDate.setDate(mDate.getDate() + pDays);
return mDate;
};
Now, if your weeks start on Sunday, pass in a "0" for the pStartOfWeek parameter, like so:
var mThisSunday = new Date().startOfWeek(0);
Similarly, if your weeks start on Monday, pass in a "1" for the pStartOfWeek parameter:
var mThisMonday = new Date().startOfWeek(1);
Regards,
Git 1.8.2 features a new option ,--remote
, that will enable exactly this behavior. Running
git submodule update --rebase --remote
will fetch the latest changes from upstream in each submodule, rebase them, and check out the latest revision of the submodule. As the documentation puts it:
--remote
This option is only valid for the update command. Instead of using the superproject’s recorded SHA-1 to update the submodule, use the status of the submodule’s remote-tracking branch.
This is equivalent to running git pull
in each submodule, which is generally exactly what you want.
(This was copied from this answer.)
Since v1.0 you can toggle word wrap:
It can also be controlled with the following settings:
Known issues:
If you'd like these bugs fixed, please vote for them.
Surely an easy fix to get rid of the '1 hours ago' problem would be to increase the window that 'an hour ago' is valid for. Change
if (delta < 5400) // 90 * 60
{
return "an hour ago";
}
into
if (delta < 7200) // 120 * 60
{
return "an hour ago";
}
This means that something that occurred 110 minutes ago will read as 'an hour ago' - this may not be perfect, but I'd say it is better than the current situation of '1 hours ago'.
Heres is another option using CSS variables . This requires a css hover definition ahead of time so I guess its not pure inline, but is very little code and flexible.
css (setup a hover state) :
.p:hover:{
color:var(--hover-color) !important,
opacity:var(--hover-opacity)
}
react:
<p style={{'color':'red','--hover-color':'blue','--hover-opacity':0.5}}>
Make sure you have this code on you component:
export class Component {
checked = true;
}
Look out for this pitfal: http://www.vertstudios.com/blog/avoiding-ajax-newline-pitfall/
Searched several houres before I found there were some linebreaks in the included files.
- Abstract class
is one which can't be instantiated, i.e. its object
cannot be created.
- Abstract method
are method's declaration without its definition.
- A Non-abstract class
can only have Non-abstract methods.
- An Abstract class
can have both the Non-abstract as well as Abstract methods.
- If the Class
has an Abstract method
then the class must also be Abstract.
- An Abstract method
must be implemented by the very first Non-Abstract sub-class.
- Abstract class
in Design patterns
are used to encapsulate the behaviors that keeps changing.
Or if you dont know the url, you can use
hadoop fs -rm -r -f /user/the/path/to/your/dir
In v1.43 is the ability to separately color the vertical rulers.
See issue Support multiple rulers with different colors - (in settings.json):
"editor.rulers": [
{
"column": 80,
"color": "#ff00FF"
},
100, // <- a ruler in the default color or as customized (with "editorRuler.foreground") at column 100
{
"column": 120,
"color": "#ff0000"
},
],
You get this error because your variable subjects
is an Object
not Array
, you can use map()
only for Array.
In case of mapping object you can do this:
{
Object.keys(subjects).map((item, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">{ subjects[item].name }</span>
</li>
))
}
jquery offers a variety of methods to hide the div in a timed manner that do not require setting up and later clearing or resetting interval timers or other event handlers. Here are a few examples.
Pure hide, one second delay
// hide in one second
$('#mydiv').delay(1000).hide(0);
Pure hide, no delay
// hide immediately
$('#mydiv').delay(0).hide(0);
Animated hide
// start hide in one second, take 1/2 second for animated hide effect
$('#mydiv').delay(1000).hide(500);
fade out
// start fade out in one second, take 300ms to fade
$('#mydiv').delay(1000).fadeOut(300);
Additionally, the methods can take a queue name or function as a second parameter (depending on method). Documentation for all the calls above and other related calls can be found here: https://api.jquery.com/category/effects/
Well yes arrays do exist, and no they're not different to lists when it comes to things like del
and append
:
>>> from array import array
>>> foo = array('i', range(5))
>>> foo
array('i', [0, 1, 2, 3, 4])
>>> del foo[:]
>>> foo
array('i')
>>> foo.append(42)
>>> foo
array('i', [42])
>>>
Differences worth noting: you need to specify the type when creating the array, and you save storage at the expense of extra time converting between the C type and the Python type when you do arr[i] = expression
or arr.append(expression)
, and lvalue = arr[i]
In controller.
Exception closes the Entity Manager. This makes troubles for bulk insert. To continue, need to redefine it.
/**
* @var \Doctrine\ORM\EntityManager
*/
$em = $this->getDoctrine()->getManager();
foreach($to_insert AS $data)
{
if(!$em->isOpen())
{
$this->getDoctrine()->resetManager();
$em = $this->getDoctrine()->getManager();
}
$entity = new \Entity();
$entity->setUniqueNumber($data['number']);
$em->persist($entity);
try
{
$em->flush();
$counter++;
}
catch(\Doctrine\DBAL\DBALException $e)
{
if($e->getPrevious()->getCode() != '23000')
{
/**
* if its not the error code for a duplicate key
* value then rethrow the exception
*/
throw $e;
}
else
{
$duplication++;
}
}
}
.png files are nice, but .ico files provide alpha-channel transparency, too, plus they give you backwards compatibility.
Have a look at which type StackOverflow uses for example (note that it's transparent):
<link rel="shortcut icon" href="http://sstatic.net/so/favicon.ico">
<link rel="apple-touch-icon" href="http://sstatic.net/so/apple-touch-icon.png">
The apple-itouch thingy is for iphone users that make a shortcut to a website.
I met such problem. Visual Studio 2008 clearly said: problem was caused by libtiff.dll. It cannot be loaded for some reasom, caused by its manifest (as a matter of fact, this dll has no manifest at all). I fixed it, when I had removed libtiff.dll from my project (but simultaneously I lost ability to open compressed TIFFs!). I recompiled aforementioned dll, but problem still remains. Interesting, that at my own machine I have no such error. Three others comps refused to load my prog. Attention!!! Here http://www.error-repair-tools.com/ppc/error.php?t=0xc0150002 one wise boy wrote, that this error was caused by problem with registry and offers repair tool. I have a solid guess, that this "repair tool" will install some malicious soft at your comp.
The distinction between a bare and non-bare Git repository is artificial and misleading since a workspace is not part of the repository and a repository doesn't require a workspace. Strictly speaking, a Git repository includes those objects that describe the state of the repository. These objects may exist in any directory, but typically exist in the .git
directory in the top-level directory of the workspace. The workspace is a directory tree that represents a particular commit in the repository, but it may exist in any directory or not at all. Environment variable $GIT_DIR
links a workspace to the repository from which it originates.
Git commands git clone
and git init
both have options --bare
that create repositories without an initial workspace. It's unfortunate that Git conflates the two separate, but related concepts of workspace and repository and then uses the confusing term bare to separate the two ideas.
It might be caused by hibernate-enhance-maven-plugin
. When I enabled enableLazyInitialization
property this exception started on happening on my lazy collection. I'm using hibernate 5.2.17.Final.
Note this two hibernate issues:
If you want to escape characters with a \
, you have addcslashes()
. For example, if you want to escape only single quotes like the question, you can do:
echo addcslashes($value, "'");
And if you want to escape '
, "
, \
, and nul
(the byte null), you can use addslashes()
:
echo addslashes($value);
Are you sure you are adding the correct user? Have you checked to see which user is set for your applications app pool?
This error will also happen if it cannot read the file for some reason; such as the file is locked or used by another application. Since this is an ASP.NET web application you will want to make sure you are not performing any actions that would require the file to be locked; unless you can guarantee you will only have one user on your page at a time.
Can you post an example of how you access the file? What type of file is it? Code snippets will help you get a more exact answer.
The Accept Ranges
header (the bit in writeHead()
) is required for the HTML5 video controls to work.
I think instead of just blindly send the full file, you should first check the Accept Ranges
header in the REQUEST, then read in and send just that bit. fs.createReadStream
support start
, and end
option for that.
So I tried an example and it works. The code is not pretty but it is easy to understand. First we process the range header to get the start/end position. Then we use fs.stat
to get the size of the file without reading the whole file into memory. Finally, use fs.createReadStream
to send the requested part to the client.
var fs = require("fs"),
http = require("http"),
url = require("url"),
path = require("path");
http.createServer(function (req, res) {
if (req.url != "/movie.mp4") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end('<video src="http://localhost:8888/movie.mp4" controls></video>');
} else {
var file = path.resolve(__dirname,"movie.mp4");
fs.stat(file, function(err, stats) {
if (err) {
if (err.code === 'ENOENT') {
// 404 Error if file not found
return res.sendStatus(404);
}
res.end(err);
}
var range = req.headers.range;
if (!range) {
// 416 Wrong range
return res.sendStatus(416);
}
var positions = range.replace(/bytes=/, "").split("-");
var start = parseInt(positions[0], 10);
var total = stats.size;
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
res.writeHead(206, {
"Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": chunksize,
"Content-Type": "video/mp4"
});
var stream = fs.createReadStream(file, { start: start, end: end })
.on("open", function() {
stream.pipe(res);
}).on("error", function(err) {
res.end(err);
});
});
}
}).listen(8888);
Franci Penov's answer is certainly the best way to go so you always return items along with all additional metadata about your entities being requested. That's the way it should be done.
but sometimes returning all data doesn't make sense, because you may not need them at all. Maybe all you need is that metadata about your requested resource. Like total count or number of pages or something else. In such case you can always have URL query tell your service not to return items but rather just metadata like:
/api/members?metaonly=true
/api/members?includeitems=0
or something similar...
SELECT DISTINCT C.valueC
FROM C
LEFT JOIN B ON C.id = B.lookupC
LEFT JOIN A ON B.id = A.lookupB
WHERE C.id IS NOT NULL
I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.
EDIT: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets.
There is no distinct join construct you could use so just stay with what you already have :)
Scroll down on that page and you'll see:
Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.
That's the SQLEXPRWT_x64_ENU.exe
download.... (WT = with tools)
Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.
That's the SQLEXPRADV_x64_ENU.exe
download ... (ADV = Advanced Services)
The SQLEXPR_x64_ENU.exe
file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.
The ascii values of the:
Up key - 224 72
Down key - 224 80
Left key - 224 75
Right key - 224 77
Each of these has two integer values for ascii value, because they are special keys, as opposed to the code for $, which is simply 36. These 2 byte special keys usually have the first digit as either 224, or 0. this can be found with the F# in windows, or the delete key.
EDIT : This may actually be unicode looking back, but they do work.
For other people trying to make a table (or something) look focused on one row using opacity. Like @Blowski said use color not opacity. Check out this fiddle: http://jsfiddle.net/2en6o43d/
.table:hover > .row:not(:hover)
If you want to add a bounding box, use a rectangle:
ax = plt.gca()
r = matplotlib.patches.Rectangle((.5, .5), .25, .1, fill=False)
ax.add_artist(r)
Example:
System.Diagnostics.Process.Start("mspaint.exe");
Compiling the Code
Copy the code and paste it into the Main method of a console application. Replace "mspaint.exe" with the path to the application you want to run.
Used This Line In Your Code
error_reporting(E_ALL ^ E_NOTICE);
I think its helf full to you.
None of the other answers worked for me, here is what eventually did.
I had to track the previous selected value of the select element and store it in the data-* attribute. Then I had to use the val() method for the select box that JQuery provides. Also, I had to make sure I was using the value attribute in my options when I populated the select box.
<body>
<select id="sel">
<option value="Apple">Apple</option> <!-- Must use the value attribute on the options in order for this to work. -->
<option value="Bannana">Bannana</option>
<option value="Cherry">Cherry</option>
</select>
</body>
<script src="https://code.jquery.com/jquery-3.5.1.js" type="text/javascript" language="javascript"></script>
<script>
$(document).ready()
{
//
// Register the necessary events.
$("#sel").on("click", sel_TrackLastChange);
$("#sel").on("keydown", sel_TrackLastChange);
$("#sel").on("change", sel_Change);
$("#sel").data("lastSelected", $("#sel").val());
}
//
// Track the previously selected value when the user either clicks on or uses the keyboard to change
// the option in the select box. Store it in the select box's data-* attribute.
function sel_TrackLastChange()
{
$("#sel").data("lastSelected", $("#sel").val());
}
//
// When the option changes on the select box, ask the user if they want to change it.
function sel_Change()
{
if(!confirm("Are you sure?"))
{
//
// If the user does not want to change the selection then use JQuery's .val() method to change
// the selection back to what it was previously.
$("#sel").val($("#sel").data("lastSelected"));
}
}
</script>
I hope this can help someone else who has the same problem as I did.
Top level classes are static by default. Inner classes are non-static by default. You can change the default for inner classes by explicitly marking them static. Top level classes, by virtue of being top-level, cannot have non-static semantics because there can be no parent class to refer to. Therefore, there is no way to change the default for top-level classes.
Create a branch where you are, then switch to master and merge it:
git branch my-temporary-work
git checkout master
git merge my-temporary-work
127.0.0.1
is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1
for connections will only receive local connections on that socket.
"localhost" is normally the hostname for the 127.0.0.1
IP address. It's usually set in /etc/hosts
(or the Windows equivalent named "hosts" somewhere under %WINDIR%
). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1
.
0.0.0.0
has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0
that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1
from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0
will accept connections on that interface too.
That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000
is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1
The problem is that you have not included bootstrap.min.css
. Also, the sequence of imports could be causing issue. Please try rearranging your resources as following:
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
Implementation in Kotlin : Retrofit 2.3.0
private fun getUnsafeOkHttpClient(mContext: Context) :
OkHttpClient.Builder? {
var mCertificateFactory : CertificateFactory =
CertificateFactory.getInstance("X.509")
var mInputStream = mContext.resources.openRawResource(R.raw.cert)
var mCertificate : Certificate = mCertificateFactory.generateCertificate(mInputStream)
mInputStream.close()
val mKeyStoreType = KeyStore.getDefaultType()
val mKeyStore = KeyStore.getInstance(mKeyStoreType)
mKeyStore.load(null, null)
mKeyStore.setCertificateEntry("ca", mCertificate)
val mTmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm()
val mTrustManagerFactory = TrustManagerFactory.getInstance(mTmfAlgorithm)
mTrustManagerFactory.init(mKeyStore)
val mTrustManagers = mTrustManagerFactory.trustManagers
val mSslContext = SSLContext.getInstance("SSL")
mSslContext.init(null, mTrustManagers, null)
val mSslSocketFactory = mSslContext.socketFactory
val builder = OkHttpClient.Builder()
builder.sslSocketFactory(mSslSocketFactory, mTrustManagers[0] as X509TrustManager)
builder.hostnameVerifier { _, _ -> true }
return builder
}
From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.
For a complete DELETE rows and reset the IDENTITY count, I use this (SQL Server 2008 R2)
USE mydb
-- ##################################################################################################################
-- DANGEROUS!!!! USE WITH CARE
-- ##################################################################################################################
DECLARE
db_cursor CURSOR FOR
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_CATALOG = 'mydb'
DECLARE @tblname VARCHAR(50)
SET @tblname = ''
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @tblname
WHILE @@FETCH_STATUS = 0
BEGIN
IF CHARINDEX('mycommonwordforalltablesIwanttodothisto', @tblname) > 0
BEGIN
EXEC('DELETE FROM ' + @tblname)
DBCC CHECKIDENT (@tblname, RESEED, 0)
END
FETCH NEXT FROM db_cursor INTO @tblname
END
CLOSE db_cursor
DEALLOCATE db_cursor
GO
My answer probably sucks compared to the real gurus out there, but using some simple math, string slicing, find and urllib, this little script will create a list containing link elements. I test google and my output seems right. Hope it helps!
import urllib
test = urllib.urlopen("http://www.google.com").read()
sane = 0
needlestack = []
while sane == 0:
curpos = test.find("href")
if curpos >= 0:
testlen = len(test)
test = test[curpos:testlen]
curpos = test.find('"')
testlen = len(test)
test = test[curpos+1:testlen]
curpos = test.find('"')
needle = test[0:curpos]
if needle.startswith("http" or "www"):
needlestack.append(needle)
else:
sane = 1
for item in needlestack:
print item
Also, if you're using Rails 3 or newer you don't have to use the up
and down
methods. You can just use change
:
class ChangeFormatInMyTable < ActiveRecord::Migration
def change
change_column :my_table, :my_column, :my_new_type
end
end
umount -a -t cifs -l
worked like a charm for me on CentOS 6.3. It saved me a server reboot.
On top of your lastest jsfiddle, you just missed one thing:
#sidebar_wrap {
width:40%;
height:200px;
background:green;
float:right;
}
#sidebar {
width:inherit;
margin-top:10px;
background-color:limegreen;
position:fixed;
max-width: 240px; /*This is you missed*/
}
But, how this will solve your problem? Simple, lets explain why is bigger than expect first.
Fixed element #sidebar
will use window width size as base to get its own size, like every other fixed element, once in this element is defined width:inherit
and #sidebar_wrap
has 40% as value in width, then will calculate window.width * 40%
, then when if your window width is bigger than your .container
width, #sidebar
will be bigger than #sidebar_wrap
.
This is way, you must set a max-width in your #sidebar_wrap
, to prevent to be bigger than #sidebar_wrap
.
Check this jsfiddle that shows a working code and explain better how this works.
Put the table in the second image on Sheet2, columns D to F.
In Sheet1, cell D2 use the formula
=iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")
copy across and down.
Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.
This could help you. It is a way to handle the touch outside event:
How to cancel an Dialog themed like Activity when touched outside the window?
By catching the event and doing nothing, I think you can prevent the closing. But what is strange though, is that the default behavior of your activity dialog should be not to close itself when you touch outside.
(PS: the code uses WindowManager.LayoutParams)
Have a look at https://wiki.debian.org/JavaPackage At the bottom of this page an other method is descibed using a command from the java-common package
Nowadays - using C++11 - you can use enum class for this:
enum class Color { RED, BLUE, WHITE };
AFAII this does exactly what you want.
On production servers I rename vendor
to vendor-<datetime>
, and during deployment will have two vendor dirs.
A HTTP cookie causes my system to choose the new vendor autoload.php
, and after testing I do a fully atomic/instant switch between them to disable the old vendor dir for all future requests, then I delete the previous dir a few days later.
This avoids any problem caused by filesystem caches I'm using in apache/php, and also allows any active PHP code to continue using the previous vendor dir.
Despite other answers recommending against it, I personally run composer install
on the server, since this is faster than rsync from my staging area (a VM on my laptop).
I use --no-dev --no-scripts --optimize-autoloader
. You should read the docs for each one to check if this is appropriate on your environment.
I would say that a scrollBottom as a direct opposite of scrollTop should be:
var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
Here is a small ugly test that works for me:
// SCROLLTESTER START //
$('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;"></h1>').insertAfter('body');
$(window).scroll(function () {
var st = $(window).scrollTop();
var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
$('#st').replaceWith('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;">scrollTop: ' + st + '<br>scrollBottom: ' + scrollBottom + '</h1>');
});
// SCROLLTESTER END //
It seems that this is the correct way window.location.assign("http://www.mozilla.org");
I also don't like using a function to handle a property which has been resolved again and again in every controller and service. Seem I'm not alone :D
Don't tried to get result with a promise as a variable, of course no way. But I found and use a solution below to access to the result as a property.
Firstly, write result to a property of your service:
app.factory('your_factory',function(){
var theParentIdResult = null;
var factoryReturn = {
theParentId: theParentIdResult,
addSiteParentId : addSiteParentId
};
return factoryReturn;
function addSiteParentId(nodeId) {
var theParentId = 'a';
var parentId = relationsManagerResource.GetParentId(nodeId)
.then(function(response){
factoryReturn.theParentIdResult = response.data;
console.log(theParentId); // #1
});
}
})
Now, we just need to ensure that method addSiteParentId
always be resolved before we accessed to property theParentId
. We can achieve this by using some ways.
Use resolve in router method:
resolve: {
parentId: function (your_factory) {
your_factory.addSiteParentId();
}
}
then in controller and other services used in your router, just call your_factory.theParentId to get your property. Referce here for more information: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx
Use run
method of app to resolve your service.
app.run(function (your_factory) { your_factory.addSiteParentId(); })
Inject it in the first controller or services of the controller. In the controller we can call all required init services. Then all remain controllers as children of main controller can be accessed to this property normally as you want.
Chose your ways depend on your context depend on scope of your variable and reading frequency of your variable.
I think what you need is to use the event.currentTarget
. This will contain the element that actually has the event listener. So if the whole <section>
has the eventlistener event.target
will be the clicked element, the <section>
will be in event.currentTarget
.
Otherwise parentNode
might be what you're looking for.
The only practical way to send credentials 100% securely is by using SSL. Using JavaScript to hash the password is not safe. Common pitfalls for client-side password hashing:
There's another secure method called SRP, but it's patented (although it is freely licensed) and there are few good implementations available.
Don't ever store passwords as plaintext in the database. Not even if you don't care about the security of your own site. Assume that some of your users will reuse the password of their online bank account. So, store the hashed password, and throw away the original. And make sure the password doesn't show up in access logs or application logs. OWASP recommends the use of Argon2 as your first choice for new applications. If this is not available, PBKDF2 or scrypt should be used instead. And finally if none of the above are available, use bcrypt.
Hashes by themselves are also insecure. For instance, identical passwords mean identical hashes--this makes hash lookup tables an effective way of cracking lots of passwords at once. Instead, store the salted hash. A salt is a string appended to the password prior to hashing - use a different (random) salt per user. The salt is a public value, so you can store them with the hash in the database. See here for more on this.
This means that you can't send the user their forgotten passwords (because you only have the hash). Don't reset the user's password unless you have authenticated the user (users must prove that they are able to read emails sent to the stored (and validated) email address.)
Security questions are insecure - avoid using them. Why? Anything a security question does, a password does better. Read PART III: Using Secret Questions in @Jens Roland answer here in this wiki.
After the user logs in, the server sends the user a session cookie. The server can retrieve the username or id from the cookie, but nobody else can generate such a cookie (TODO explain mechanisms).
Cookies can be hijacked: they are only as secure as the rest of the client's machine and other communications. They can be read from disk, sniffed in network traffic, lifted by a cross-site scripting attack, phished from a poisoned DNS so the client sends their cookies to the wrong servers. Don't send persistent cookies. Cookies should expire at the end of the client session (browser close or leaving your domain).
If you want to autologin your users, you can set a persistent cookie, but it should be distinct from a full-session cookie. You can set an additional flag that the user has auto-logged in, and needs to log in for real for sensitive operations. This is popular with shopping sites that want to provide you with a seamless, personalized shopping experience but still protect your financial details. For example, when you return to visit Amazon, they show you a page that looks like you're logged in, but when you go to place an order (or change your shipping address, credit card etc.), they ask you to confirm your password.
Financial websites such as banks and credit cards, on the other hand, only have sensitive data and should not allow auto-login or a low-security mode.
I'm surprised noone's voted up Shao's answer that, as I understand it, it is impossible to do what's asked in standard C99, since converting a pointer to an integral type formally is undefined behavior. (Apart from the standard allowing conversion of uintptr_t
<-> void*
, but the standard does not seem to allow doing any manipulations of the uintptr_t
value and then converting it back.)
Use jQuery .siblings()
to select the matching sibling.
$(this).siblings('.bidbutton');
I found that stimulating an update in "natural" sequence was an easier route than force-pushing things.
Supposing that the repo is already created on github and you may have also put some stuff into the README.md .
On your computer, open terminal and git clone [repo URL]
You'll see a new folder will have been created bearing your repo's name. Feel free to rename it - doesn't matter.
Move your code, files etc into this folder. Edit the README.md if you have to.
Now open Terminal / command prompt, get inside that folder and do things as if you are making the next update to the repo:
git add .
git commit -m "v2"
git push origin master
Note: at the commit command git may reject, asking to configure the user email and password first. Follow the steps as given on screen, then run the commit command again.
You can try using Microsoft's Sign Tool
You download it as part of the Windows SDK for Windows Server 2008 and .NET 3.5. Once downloaded you can use it from the command line like so:
signtool sign /a MyFile.exe
This signs a single executable, using the "best certificate" available. (If you have no certificate, it will show a SignTool error message.)
Or you can try:
signtool signwizard
This will launch a wizard that will walk you through signing your application. (This option is not available after Windows SDK 7.0.)
If you'd like to get a hold of certificate that you can use to test your process of signing the executable you can use the .NET tool Makecert.
Certificate Creation Tool (Makecert.exe)
Once you've created your own certificate and have used it to sign your executable, you'll need to manually add it as a Trusted Root CA for your machine in order for UAC to tell the user running it that it's from a trusted source. Important. Installing a certificate as ROOT CA will endanger your users privacy. Look what happened with DELL. You can find more information for accomplishing this both in code and through Windows in:
Stack Overflow question Install certificates in to the Windows Local user certificate store in C#
Installing a Self-Signed Certificate as a Trusted Root CA in Windows Vista
Hopefully that provides some more information for anyone attempting to do this!
Here answer for your code as whole:
key =10
files = ("ME%i.txt" % i for i in range(key))
#opening
files = [ open(filename, 'w') for filename in files]
# processing
for i, file in zip(range(key),files):
file.write(str(i))
# closing
for openfile in files:
openfile.close()
This probably because of your gzip version incompatibility.
Check these points first:
which gzip
/usr/bin/gzip or /bin/gzip
It should be either /bin/gzip or /usr/bin/gzip. If your gzip points to some other gzip application please try by removing that path from your PATH env variable.
Next is
gzip -V
gzip 1.3.5 (2002-09-30)
Your problem can be resolve with these check points.
If you select the log entry to which you want to revert to then you can click on "Reset to this commit". Only use this option if you didn't push the reverse commit changes. If you're worried about losing the changes then you can use the soft mode which will leave a set of uncommitted changes (what you just changed). Using the mixed resets the working copy but keeps those changes, and a hard will just get rid of the changes entirely. Here's some screenshots:
Here is what one can do for going on the way @iconoclast was wondering about in their comment on another answer.
use crontab for user or an /etc/crontab
to create file /tmp/hour
:
# m h dom mon dow user command
0 * * * * root /usr/bin/touch /tmp/hour > /dev/null 2>&1
and then use this to run your command:
find /tmp/ -daystart -maxdepth 1 -not -newer /tmp/hour -type f -name "for_one_hour_files*" -exec do_something {} \;
You can do this with the additional effects in jQuery UI: See here for details
Quick example:
$(this).hide("slide", { direction: "left" }, 1000);
$(this).show("slide", { direction: "left" }, 1000);
try this one:
<table style="border:1px solid">
<tr>
<td style="min-width:50px">one</td>
<td style="min-width:100px">two</td>
</tr>
</table>
_x000D_
I might be misunderstanding your question, so apologies if I am.
If you're looking for the words "Quid", "Application Number", etc. to be bold, just wrap them in <strong>
tags:
<strong>Quid</strong>: ...
Hope that helps!
This should solve your problem:
select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);
Give a look also as this SQL Fiddle for test.
If you only need the bool
result, just use the return value and ignore the out
parameter.
bool successfullyParsed = int.TryParse(str, out ignoreMe);
if (successfullyParsed){
// ...
}
Edit: Meanwhile you can also have a look at the original source code:
If i want to know how something is actually implemented, i'm using ILSpy
to decompile the .NET-code.
This is the result:
// int
/// <summary>Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.</summary>
/// <returns>true if s was converted successfully; otherwise, false.</returns>
/// <param name="s">A string containing a number to convert. </param>
/// <param name="result">When this method returns, contains the 32-bit signed integer value equivalent to the number contained in s, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null, is not of the correct format, or represents a number less than <see cref="F:System.Int32.MinValue"></see> or greater than <see cref="F:System.Int32.MaxValue"></see>. This parameter is passed uninitialized. </param>
/// <filterpriority>1</filterpriority>
public static bool TryParse(string s, out int result)
{
return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
// System.Number
internal unsafe static bool TryParseInt32(string s, NumberStyles style, NumberFormatInfo info, out int result)
{
byte* stackBuffer = stackalloc byte[1 * 114 / 1];
Number.NumberBuffer numberBuffer = new Number.NumberBuffer(stackBuffer);
result = 0;
if (!Number.TryStringToNumber(s, style, ref numberBuffer, info, false))
{
return false;
}
if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
{
if (!Number.HexNumberToInt32(ref numberBuffer, ref result))
{
return false;
}
}
else
{
if (!Number.NumberToInt32(ref numberBuffer, ref result))
{
return false;
}
}
return true;
}
And no, i cannot see any Try-Catchs
on the road:
// System.Number
private unsafe static bool TryStringToNumber(string str, NumberStyles options, ref Number.NumberBuffer number, NumberFormatInfo numfmt, bool parseDecimal)
{
if (str == null)
{
return false;
}
fixed (char* ptr = str)
{
char* ptr2 = ptr;
if (!Number.ParseNumber(ref ptr2, options, ref number, numfmt, parseDecimal) || ((ptr2 - ptr / 2) / 2 < str.Length && !Number.TrailingZeros(str, (ptr2 - ptr / 2) / 2)))
{
return false;
}
}
return true;
}
// System.Number
private unsafe static bool ParseNumber(ref char* str, NumberStyles options, ref Number.NumberBuffer number, NumberFormatInfo numfmt, bool parseDecimal)
{
number.scale = 0;
number.sign = false;
string text = null;
string text2 = null;
string str2 = null;
string str3 = null;
bool flag = false;
string str4;
string str5;
if ((options & NumberStyles.AllowCurrencySymbol) != NumberStyles.None)
{
text = numfmt.CurrencySymbol;
if (numfmt.ansiCurrencySymbol != null)
{
text2 = numfmt.ansiCurrencySymbol;
}
str2 = numfmt.NumberDecimalSeparator;
str3 = numfmt.NumberGroupSeparator;
str4 = numfmt.CurrencyDecimalSeparator;
str5 = numfmt.CurrencyGroupSeparator;
flag = true;
}
else
{
str4 = numfmt.NumberDecimalSeparator;
str5 = numfmt.NumberGroupSeparator;
}
int num = 0;
char* ptr = str;
char c = *ptr;
while (true)
{
if (!Number.IsWhite(c) || (options & NumberStyles.AllowLeadingWhite) == NumberStyles.None || ((num & 1) != 0 && ((num & 1) == 0 || ((num & 32) == 0 && numfmt.numberNegativePattern != 2))))
{
bool flag2;
char* ptr2;
if ((flag2 = ((options & NumberStyles.AllowLeadingSign) != NumberStyles.None && (num & 1) == 0)) && (ptr2 = Number.MatchChars(ptr, numfmt.positiveSign)) != null)
{
num |= 1;
ptr = ptr2 - (IntPtr)2 / 2;
}
else
{
if (flag2 && (ptr2 = Number.MatchChars(ptr, numfmt.negativeSign)) != null)
{
num |= 1;
number.sign = true;
ptr = ptr2 - (IntPtr)2 / 2;
}
else
{
if (c == '(' && (options & NumberStyles.AllowParentheses) != NumberStyles.None && (num & 1) == 0)
{
num |= 3;
number.sign = true;
}
else
{
if ((text == null || (ptr2 = Number.MatchChars(ptr, text)) == null) && (text2 == null || (ptr2 = Number.MatchChars(ptr, text2)) == null))
{
break;
}
num |= 32;
text = null;
text2 = null;
ptr = ptr2 - (IntPtr)2 / 2;
}
}
}
}
c = *(ptr += (IntPtr)2 / 2);
}
int num2 = 0;
int num3 = 0;
while (true)
{
if ((c >= '0' && c <= '9') || ((options & NumberStyles.AllowHexSpecifier) != NumberStyles.None && ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))))
{
num |= 4;
if (c != '0' || (num & 8) != 0)
{
if (num2 < 50)
{
number.digits[(IntPtr)(num2++)] = c;
if (c != '0' || parseDecimal)
{
num3 = num2;
}
}
if ((num & 16) == 0)
{
number.scale++;
}
num |= 8;
}
else
{
if ((num & 16) != 0)
{
number.scale--;
}
}
}
else
{
char* ptr2;
if ((options & NumberStyles.AllowDecimalPoint) != NumberStyles.None && (num & 16) == 0 && ((ptr2 = Number.MatchChars(ptr, str4)) != null || (flag && (num & 32) == 0 && (ptr2 = Number.MatchChars(ptr, str2)) != null)))
{
num |= 16;
ptr = ptr2 - (IntPtr)2 / 2;
}
else
{
if ((options & NumberStyles.AllowThousands) == NumberStyles.None || (num & 4) == 0 || (num & 16) != 0 || ((ptr2 = Number.MatchChars(ptr, str5)) == null && (!flag || (num & 32) != 0 || (ptr2 = Number.MatchChars(ptr, str3)) == null)))
{
break;
}
ptr = ptr2 - (IntPtr)2 / 2;
}
}
c = *(ptr += (IntPtr)2 / 2);
}
bool flag3 = false;
number.precision = num3;
number.digits[(IntPtr)num3] = '\0';
if ((num & 4) != 0)
{
if ((c == 'E' || c == 'e') && (options & NumberStyles.AllowExponent) != NumberStyles.None)
{
char* ptr3 = ptr;
c = *(ptr += (IntPtr)2 / 2);
char* ptr2;
if ((ptr2 = Number.MatchChars(ptr, numfmt.positiveSign)) != null)
{
c = *(ptr = ptr2);
}
else
{
if ((ptr2 = Number.MatchChars(ptr, numfmt.negativeSign)) != null)
{
c = *(ptr = ptr2);
flag3 = true;
}
}
if (c >= '0' && c <= '9')
{
int num4 = 0;
do
{
num4 = num4 * 10 + (int)(c - '0');
c = *(ptr += (IntPtr)2 / 2);
if (num4 > 1000)
{
num4 = 9999;
while (c >= '0' && c <= '9')
{
c = *(ptr += (IntPtr)2 / 2);
}
}
}
while (c >= '0' && c <= '9');
if (flag3)
{
num4 = -num4;
}
number.scale += num4;
}
else
{
ptr = ptr3;
c = *ptr;
}
}
while (true)
{
if (!Number.IsWhite(c) || (options & NumberStyles.AllowTrailingWhite) == NumberStyles.None)
{
bool flag2;
char* ptr2;
if ((flag2 = ((options & NumberStyles.AllowTrailingSign) != NumberStyles.None && (num & 1) == 0)) && (ptr2 = Number.MatchChars(ptr, numfmt.positiveSign)) != null)
{
num |= 1;
ptr = ptr2 - (IntPtr)2 / 2;
}
else
{
if (flag2 && (ptr2 = Number.MatchChars(ptr, numfmt.negativeSign)) != null)
{
num |= 1;
number.sign = true;
ptr = ptr2 - (IntPtr)2 / 2;
}
else
{
if (c == ')' && (num & 2) != 0)
{
num &= -3;
}
else
{
if ((text == null || (ptr2 = Number.MatchChars(ptr, text)) == null) && (text2 == null || (ptr2 = Number.MatchChars(ptr, text2)) == null))
{
break;
}
text = null;
text2 = null;
ptr = ptr2 - (IntPtr)2 / 2;
}
}
}
}
c = *(ptr += (IntPtr)2 / 2);
}
if ((num & 2) == 0)
{
if ((num & 8) == 0)
{
if (!parseDecimal)
{
number.scale = 0;
}
if ((num & 16) == 0)
{
number.sign = false;
}
}
str = ptr;
return true;
}
}
str = ptr;
return false;
}
When you're using get()
you get a collection. In this case you need to iterate over it to get properties:
@foreach ($collection as $object)
{{ $object->title }}
@endforeach
Or you could just get one of objects by it's index:
{{ $collection[0]->title }}
Or get first object from collection:
{{ $collection->first() }}
When you're using find()
or first()
you get an object, so you can get properties with simple:
{{ $object->title }}
follow the python2.7 document, you have to use calendar.timegm() instead of time.mktime()
>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(calendar.timegm(d.timetuple()))
datetime.datetime(2011, 1, 1, 0, 0)
Webpack
is a bundler. Like Browserfy
it looks in the codebase for module requests (require
or import
) and resolves them recursively. What is more, you can configure Webpack
to resolve not just JavaScript-like modules, but CSS, images, HTML, literally everything. What especially makes me excited about Webpack
, you can combine both compiled and dynamically loaded modules in the same app. Thus one get a real performance boost, especially over HTTP/1.x. How exactly you you do it I described with examples here http://dsheiko.com/weblog/state-of-javascript-modules-2017/
As an alternative for bundler one can think of Rollup.js
(https://rollupjs.org/), which optimizes the code during compilation, but stripping all the found unused chunks.
For AMD
, instead of RequireJS
one can go with native ES2016 module system
, but loaded with System.js
(https://github.com/systemjs/systemjs)
Besides, I would point that npm
is often used as an automating tool like grunt
or gulp
. Check out https://docs.npmjs.com/misc/scripts. I personally go now with npm scripts only avoiding other automation tools, though in past I was very much into grunt
. With other tools you have to rely on countless plugins for packages, that often are not good written and not being actively maintained. npm
knows its packages, so you call to any of locally installed packages by name like:
{
"scripts": {
"start": "npm http-server"
},
"devDependencies": {
"http-server": "^0.10.0"
}
}
Actually you as a rule do not need any plugin if the package supports CLI.
For whom want to install ext-dom on php 7.1 and up run this command:
sudo apt install php-xml
For rounding, you should probably use the C functions defined in math.h.
int roundedX = round(x);
Hold down Option and double click on round
in Xcode and it will show you the man page with various functions for rounding different types.
var str = "foo/bar/test.html";
var lastSlash = str.lastIndexOf("/");
alert(str.substring(lastSlash+1));
You can change time() to now() for it to work
from datetime import datetime, timedelta
datetime.now() + timedelta(hours=1)
Using a DispatcherTimer:
var _activeTimer = new DispatcherTimer {
Interval = TimeSpan.FromMinutes(5)
};
_activeTimer.Tick += delegate (object sender, EventArgs e) {
YourMethod();
};
_activeTimer.Start();
Alternative ways of iteration through array/string with side effects
var str = '21,32,234,223';_x000D_
var substr = str.split(',');_x000D_
_x000D_
substr.reduce((a,x)=> console.log('reduce',x), 0) // return undefined_x000D_
_x000D_
substr.every(x=> { console.log('every',x); return true}) // return true_x000D_
_x000D_
substr.some(x=> { console.log('some',x); return false}) // return false_x000D_
_x000D_
substr.map(x=> console.log('map',x)); // return array_x000D_
_x000D_
str.replace(/(\d+)/g, x=> console.log('replace',x)) // return string
_x000D_
To run or convert batch files externally from PowerShell (particularly if you wish to sign all your scheduled task scripts with a certificate) I simply create a PowerShell script, e.g. deletefolders.ps1.
Input the following into the script:
cmd.exe /c "rd /s /q C:\#TEMP\test1"
cmd.exe /c "rd /s /q C:\#TEMP\test2"
cmd.exe /c "rd /s /q C:\#TEMP\test3"
*Each command needs to be put on a new line calling cmd.exe again.
This script can now be signed and run from PowerShell outputting the commands to command prompt / cmd
directly.
It is a much safer way than running batch files!
Free for non-commercial use.
Includes plugins for jQuery, Node.js, WordPress, Drupal, Joomla, Microsoft TypeScript, etc...
Some screenshots of some of the demos:
An alternative approach would be:
df1 = sqlContext.createDataFrame(
[(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
("x1", "x2", "x3"))
df2 = sqlContext.createDataFrame(
[(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x4"))
df = df1.join(df2, ['x1','x2'])
df.show()
which outputs:
+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
| 2| b|3.0|0.0|
+---+---+---+---+
With the main advantage being that the columns on which the tables are joined are not duplicated in the output, reducing the risk of encountering errors such as org.apache.spark.sql.AnalysisException: Reference 'x1' is ambiguous, could be: x1#50L, x1#57L.
Whenever the columns in the two tables have different names, (let's say in the example above, df2
has the columns y1
, y2
and y4
), you could use the following syntax:
df = df1.join(df2.withColumnRenamed('y1','x1').withColumnRenamed('y2','x2'), ['x1','x2'])
I've created a "lazy load" plugin which might help. Here is the a possible way to get the job done with it in your case:
$('img').lazyloadanything({
'onLoad': function(e, LLobj) {
var $img = LLobj.$element;
var src = $img.attr('data-src');
$img.css('background-image', 'url("'+src+'")');
}
});
It is simple like maosmurf's example but still gives you the "lazy load" functionality of event firing when the element comes into view.
Function already exists: timezone('UTC'::text, now())
used Martin's suggestion with a little tweak to add time stamp to the file name:
forfiles /p [foldername] /m rsync2.log /c "cmd /c ren @file %DATE:~6,4%%DATE:~3,2%%DATE:~0,2%_%time:~-11,2%-%time:~-8,2%-%time:~-5,2%-@file
For the 10:17:21 23/10/2019 The result is:
20191023_10-17-21-rsync2.log
Why do not use array_diff?
$array = array(
1 => 'Awaiting for Confirmation',
2 => 'Asssigned',
3 => 'In Progress',
4 => 'Completed',
5 => 'Mark As Spam',
);
$to_delete = array('Completed', 'Mark As Spam');
$array = array_diff($array, $to_delete);
Just note that your array would be reindexed.
To center a view in Framelayout, there are some available tricks. The simplest one I used for my Webview and Progressbar(very similar to your two object layout), I just added android:layout_gravity="center"
Here is complete XML in case if someone else needs the same thing to do
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WebviewPDFActivity"
android:layout_gravity="center"
>
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ProgressBar
android:id="@+id/progress_circular"
android:layout_width="250dp"
android:layout_height="250dp"
android:visibility="visible"
android:layout_gravity="center"
/>
</FrameLayout>
Here is my output
To test if object is an instance of class a:
[yourObject isKindOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of
// given class or an instance of any class that inherits from that class.
or
[yourObject isMemberOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of a
// given class.
To get object's class name you can use NSStringFromClass
function:
NSString *className = NSStringFromClass([yourObject class]);
or c-function from objective-c runtime api:
#import <objc/runtime.h>
/* ... */
const char* className = class_getName([yourObject class]);
NSLog(@"yourObject is a: %s", className);
EDIT: In Swift
if touch.view is UIPickerView {
// touch.view is of type UIPickerView
}
Either you can use CSV functions or PHPExcel
or you can try like below
<?php
$file="demo.xls";
$test="<table ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>
The header for .xlsx files is Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
I just figured it out! What I did was I created the batch file like I had it originally:
net use P: "\\server\foldername\foldername"
I then saved it to the desktop and right clicked the properties and checked run as administrator. I then copied the file to C:\Users\"TheUser"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Where "TheUser" was the desired user I wanted to add it to.
These answers either don't give unique values, or are so long (one even adding an external library to do such a simple task).
1. generate a random number.
2. if we have this random already then goto 1, else keep it.
3. if we don't have desired quantity of randoms, then goto 1.
function uniqueRandoms(qty, min, max){_x000D_
var rnd, arr=[];_x000D_
do { do { rnd=Math.floor(Math.random()*max)+min }_x000D_
while(arr.includes(rnd))_x000D_
arr.push(rnd);_x000D_
} while(arr.length<qty)_x000D_
return arr;_x000D_
}_x000D_
_x000D_
//generate 5 unique numbers between 1 and 10_x000D_
console.log( uniqueRandoms(5, 1, 10) );
_x000D_
...and a compressed version of the same function:
function uniqueRandoms(qty,min,max){var a=[];do{do{r=Math.floor(Math.random()*max)+min}while(a.includes(r));a.push(r)}while(a.length<qty);return a}
This answer by Jaap :
<div class="image"></div>?
and in CSS :
div.image {
content:url(http://placehold.it/350x150);
}?
you can try it on this link : http://jsfiddle.net/XAh2d/
this is a link about css content http://css-tricks.com/css-content/
This has been tested on Chrome, firefox and Safari. (I'm on a mac, so if someone has the result on IE, tell me to add it)
Use LINQ Aggregate
method to convert array of integers to a comma separated string
var intArray = new []{1,2,3,4};
string concatedString = intArray.Aggregate((a, b) =>Convert.ToString(a) + "," +Convert.ToString( b));
Response.Write(concatedString);
output will be
1,2,3,4
This is one of the solution you can use if you have not .net 4 installed.
This is relatively simple example and worked for me.
hr {
width: 70%;
margin-left: auto;
margin-right: auto;
}
Resource: https://www.w3docs.com/snippets/css/how-to-style-a-horizontal-line.html
Here is how I would fix it, using a code snippet to give you a basic idea:
public class IFrame1 extends LoadableComponent<IFrame1> {
private RemoteWebDriver driver;
@FindBy(id = "iFrame1TextFieldTestInputControlID" ) public WebElement iFrame1TextFieldInput;
@FindBy(id = "iFrame1TextFieldTestProcessButtonID" ) public WebElement copyButton;
public IFrame1( RemoteWebDriver drv ) {
super();
this.driver = drv;
this.driver.switchTo().defaultContent();
waitTimer(1, 1000);
this.driver.switchTo().frame("BodyFrame1");
LOGGER.info("IFrame1 constructor...");
}
@Override
protected void isLoaded() throws Error {
LOGGER.info("IFrame1.isLoaded()...");
PageFactory.initElements( driver, this );
try {
assertTrue( "Page visible title is not yet available.",
driver.findElementByCssSelector("body form#webDriverUnitiFrame1TestFormID h1")
.getText().equals("iFrame1 Test") );
} catch ( NoSuchElementException e) {
LOGGER.info("No such element." );
assertTrue("No such element.", false);
}
}
/**
* Method: load
* Overidden method from the LoadableComponent class.
* @return void
* @throws null
*/
@Override
protected void load() {
LOGGER.info("IFrame1.load()...");
Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring( NoSuchElementException.class )
.ignoring( StaleElementReferenceException.class ) ;
wait.until( ExpectedConditions.presenceOfElementLocated(
By.cssSelector("body form#webDriverUnitiFrame1TestFormID h1") ) );
}
....
the easiest way is to use position:absolute
on both elements. You can absolutely position relative to the page, or you can absolutely position relative to a container div by setting the container div to position:relative
<div id="container" style="position:relative;">
<div id="div1" style="position:absolute; top:0; left:0;"></div>
<div id="div2" style="position:absolute; top:0; left:0;"></div>
</div>
Try this:
moment("02/26/1978", "MM/DD/YYYY").fromNow().split(" ")[0];
Explanation:
We receive string something like this: '23 days ago'. Split it to array: ['23', 'days', 'ago'] and then take first item '23'.
The Extented WPF Toolkit has one: NumericUpDown
You can try the cases
env in amsmath.
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{equation}
f(x)=\begin{cases}
1, & \text{if $x<0$}.\\
0, & \text{otherwise}.
\end{cases}
\end{equation}
\end{document}
If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :
For eg.
Dim dt As New DataTable
dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))
dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")
its work short code
$('.SeeMore2').click(function(){
var $this = $(this).toggleClass('SeeMore2');
if($(this).hasClass('SeeMore2'))
{
$(this).text('See More');
} else {
$(this).text('See Less');
}
});
The @Tim Pietzcker's answer here
(?<=\[)[^]]+(?=\])
is almost the one I've been looking for. But there is one issue that some legacy browsers can fail on positive lookbehind. So I had to made my day by myself :). I manged to write this:
/([^[]+(?=]))/g
Maybe it will help someone.
console.log("this is a [sample] string with [some] special words. [another one]".match(/([^[]+(?=]))/g));
_x000D_
Updated for iOS 8.0
Since iOS 8.0, you will need to use UIAlertController as the following:
-(void)alertMessage:(NSString*)message
{
UIAlertController* alert = [UIAlertController
alertControllerWithTitle:@"Alert"
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction
actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
Where self in my example is a UIViewController, which implements "presentViewController" method for a popup.
David
If you are using ES6 and Express, try this destructuring
approach:
const {id, since, fields, anotherField} = request.query;
In context:
const express = require('express');
const app = express();
app.get('/', function(req, res){
const {id, since, fields, anotherField} = req.query;
});
app.listen(3000);
You can use default values with destructuring
too:
// sample request for testing_x000D_
const req = {_x000D_
query: {_x000D_
id: '123',_x000D_
fields: ['a', 'b', 'c']_x000D_
}_x000D_
}_x000D_
_x000D_
const {_x000D_
id,_x000D_
since = new Date().toString(),_x000D_
fields = ['x'],_x000D_
anotherField = 'default'_x000D_
} = req.query;_x000D_
_x000D_
console.log(id, since, fields, anotherField)
_x000D_
I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:
if ($_POST['action'] == 'addRunner')
I used the :not() on the selection to stop it from clearing the hidden field.
You can wrap input stream with PushbackInputStream. PushbackInputStream allows to unread ("write back") bytes which were already read, so you can do like this:
public class StreamTest {
public static void main(String[] args) throws IOException {
byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
InputStream originalStream = new ByteArrayInputStream(bytes);
byte[] readBytes = getBytes(originalStream, 3);
printBytes(readBytes); // prints: 1 2 3
readBytes = getBytes(originalStream, 3);
printBytes(readBytes); // prints: 4 5 6
// now let's wrap it with PushBackInputStream
originalStream = new ByteArrayInputStream(bytes);
InputStream wrappedStream = new PushbackInputStream(originalStream, 10); // 10 means that maximnum 10 characters can be "written back" to the stream
readBytes = getBytes(wrappedStream, 3);
printBytes(readBytes); // prints 1 2 3
((PushbackInputStream) wrappedStream).unread(readBytes, 0, readBytes.length);
readBytes = getBytes(wrappedStream, 3);
printBytes(readBytes); // prints 1 2 3
}
private static byte[] getBytes(InputStream is, int howManyBytes) throws IOException {
System.out.print("Reading stream: ");
byte[] buf = new byte[howManyBytes];
int next = 0;
for (int i = 0; i < howManyBytes; i++) {
next = is.read();
if (next > 0) {
buf[i] = (byte) next;
}
}
return buf;
}
private static void printBytes(byte[] buffer) throws IOException {
System.out.print("Reading stream: ");
for (int i = 0; i < buffer.length; i++) {
System.out.print(buffer[i] + " ");
}
System.out.println();
}
}
Please note that PushbackInputStream stores internal buffer of bytes so it really creates a buffer in memory which holds bytes "written back".
Knowing this approach we can go further and combine it with FilterInputStream. FilterInputStream stores original input stream as a delegate. This allows to create new class definition which allows to "unread" original data automatically. The definition of this class is following:
public class TryReadInputStream extends FilterInputStream {
private final int maxPushbackBufferSize;
/**
* Creates a <code>FilterInputStream</code>
* by assigning the argument <code>in</code>
* to the field <code>this.in</code> so as
* to remember it for later use.
*
* @param in the underlying input stream, or <code>null</code> if
* this instance is to be created without an underlying stream.
*/
public TryReadInputStream(InputStream in, int maxPushbackBufferSize) {
super(new PushbackInputStream(in, maxPushbackBufferSize));
this.maxPushbackBufferSize = maxPushbackBufferSize;
}
/**
* Reads from input stream the <code>length</code> of bytes to given buffer. The read bytes are still avilable
* in the stream
*
* @param buffer the destination buffer to which read the data
* @param offset the start offset in the destination <code>buffer</code>
* @aram length how many bytes to read from the stream to buff. Length needs to be less than
* <code>maxPushbackBufferSize</code> or IOException will be thrown
*
* @return number of bytes read
* @throws java.io.IOException in case length is
*/
public int tryRead(byte[] buffer, int offset, int length) throws IOException {
validateMaxLength(length);
// NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
// because read() guarantees to read a byte
int bytesRead = 0;
int nextByte = 0;
for (int i = 0; (i < length) && (nextByte >= 0); i++) {
nextByte = read();
if (nextByte >= 0) {
buffer[offset + bytesRead++] = (byte) nextByte;
}
}
if (bytesRead > 0) {
((PushbackInputStream) in).unread(buffer, offset, bytesRead);
}
return bytesRead;
}
public byte[] tryRead(int maxBytesToRead) throws IOException {
validateMaxLength(maxBytesToRead);
ByteArrayOutputStream baos = new ByteArrayOutputStream(); // as ByteArrayOutputStream to dynamically allocate internal bytes array instead of allocating possibly large buffer (if maxBytesToRead is large)
// NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
// because read() guarantees to read a byte
int nextByte = 0;
for (int i = 0; (i < maxBytesToRead) && (nextByte >= 0); i++) {
nextByte = read();
if (nextByte >= 0) {
baos.write((byte) nextByte);
}
}
byte[] buffer = baos.toByteArray();
if (buffer.length > 0) {
((PushbackInputStream) in).unread(buffer, 0, buffer.length);
}
return buffer;
}
private void validateMaxLength(int length) throws IOException {
if (length > maxPushbackBufferSize) {
throw new IOException(
"Trying to read more bytes than maxBytesToRead. Max bytes: " + maxPushbackBufferSize + ". Trying to read: " +
length);
}
}
}
This class has two methods. One for reading into existing buffer (defintion is analogous to calling public int read(byte b[], int off, int len)
of InputStream class). Second which returns new buffer (this may be more effective if the size of buffer to read is unknown).
Now let's see our class in action:
public class StreamTest2 {
public static void main(String[] args) throws IOException {
byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
InputStream originalStream = new ByteArrayInputStream(bytes);
byte[] readBytes = getBytes(originalStream, 3);
printBytes(readBytes); // prints: 1 2 3
readBytes = getBytes(originalStream, 3);
printBytes(readBytes); // prints: 4 5 6
// now let's use our TryReadInputStream
originalStream = new ByteArrayInputStream(bytes);
InputStream wrappedStream = new TryReadInputStream(originalStream, 10);
readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // NOTE: no manual call to "unread"(!) because TryReadInputStream handles this internally
printBytes(readBytes); // prints 1 2 3
readBytes = ((TryReadInputStream) wrappedStream).tryRead(3);
printBytes(readBytes); // prints 1 2 3
readBytes = ((TryReadInputStream) wrappedStream).tryRead(3);
printBytes(readBytes); // prints 1 2 3
// we can also call normal read which will actually read the bytes without "writing them back"
readBytes = getBytes(wrappedStream, 3);
printBytes(readBytes); // prints 1 2 3
readBytes = getBytes(wrappedStream, 3);
printBytes(readBytes); // prints 4 5 6
readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // now we can try read next bytes
printBytes(readBytes); // prints 7 8 9
readBytes = ((TryReadInputStream) wrappedStream).tryRead(3);
printBytes(readBytes); // prints 7 8 9
}
}
If you're using Bash you could also use one of the following commands:
printf '%(%Y%m%d%H%M%S)T' # prints the current time
printf '%(%Y%m%d%H%M%S)T' -1 # same as above
printf '%(%Y%m%d%H%M%S)T' -2 # prints the time the shell was invoked
You can use the Option -v varname
to store the result in $varname
instead of printing it to stdout:
printf -v varname '%(%Y%m%d%H%M%S)T'
While the date command will always be executed in a subshell (i.e. in a separate process) printf is a builtin command and will therefore be faster.
I was wondering how to do this myself; it seems Gmail has since silently implemented this feature. I created the following filter:
Matches: subject:([test])
Do this: Skip Inbox
And then I sent a message with the subject
[test] foo
And the message was archived! So it seems all that is necessary is to create a filter for the subject prefix you wish to handle.
x % n == 0
which means the x/n and the value of reminder will taken as a result and compare with zero....
example: 4/5==0
4/5 reminder is 4
4==0 (False)
Lodash:
var args = _.toArray(arguments);
in action:
(function(){ console.log(_.toArray(arguments).splice(1)); })(1, 2, 3)
produces:
[2,3]
Another interesting solution in ORACLE PL/SQL:
SELECT LEVEL n
FROM DUAL
CONNECT BY LEVEL <= 100;
DateTime values should be inserted as if they are strings surrounded by single quotes:
'20100301'
SQL Server allows for many accepted date formats and it should be the case that most development libraries provide a series of classes or functions to insert datetime values properly. However, if you are doing it manually, it is important to distinguish the date format using DateFormat
and to use generalized format:
Set DateFormat MDY --indicates the general format is Month Day Year
Insert Table( DateTImeCol )
Values( '2011-03-12' )
By setting the dateformat, SQL Server now assumes that my format is YYYY-MM-DD
instead of YYYY-DD-MM
.
SQL Server also recognizes a generic format that is always interpreted the same way: YYYYMMDD
e.g. 20110312
.
If you are asking how to insert the current date and time using T-SQL, then I would recommend using the keyword CURRENT_TIMESTAMP
. For example:
Insert Table( DateTimeCol )
Values( CURRENT_TIMESTAMP )
java -jar server-0.0.1-SNAPSHOT.jar --spring.config.location=application-prod.properties
As i understood your query, You just run this script and get Total Null,Total NotNull rows,
select count(*) - count(a) as 'Null', count(a) as 'Not Null' from us;
Do this:
list.ForEach(i => Console.Write("{0}\t", i));
EDIT: To others that have responded - he wants them all on the same line, with tabs between them. :)
Try Using this query for searching special character records
SELECT *
FROM tableName
WHERE fieldName REGEXP '[^a-zA-Z0-9@:. \'\-`,\&]'
The usual cause of this is that you're also using Prototype, MooTools, or some other library that makes use of the $
symbol, and you're including that library after jQuery, and so that library is "winning" (taking $
for itself). So the return value of $
isn't a jQuery instance, and so it doesn't have jQuery methods on it (like on
).
You can use jQuery with those other libraries, but if you do, you have to use the jQuery
symbol rather than its alias $
, e.g.:
jQuery('body').on(...);
And it's usually best if you add this immediately after your script
tag including jQuery, before the one including the other library:
<script>jQuery.noConflict();</script>
...although it's not required if you load the other library after jQuery (it is if you load the other library first).
Using multiple full-function DOM manipulation libraries on the same page isn't ideal, though, just in terms of page weight. So if you can stick with just Prototype/MooTools/whatever or just jQuery, that's usually better.
To do this, I would strongly consider wrapping a Text
component in a TouchableOpacity
. When a TouchableOpacity
is touched, it fades (becomes less opaque). This gives the user immediate feedback when touching the text and provides for an improved user experience.
You can use the onPress
property on the TouchableOpacity
to make the link happen:
<TouchableOpacity onPress={() => Linking.openURL('http://google.com')}>
<Text style={{color: 'blue'}}>
Google
</Text>
</TouchableOpacity>
Recompile without optimizations (-O0 on gcc).
Does your console app require user interaction? If so, that's a serious no-no and you should redesign your application. While there are some hacks to make this sort of work in older versions of the OS, this is guaranteed to break in the future.
If your app does not require user interaction, then perhaps your problem is related to the user the service is running as. Try making sure that you run as the correct user, or that the user and/or resources you are using have the right permissions.
If you require some kind of user-interaction, then you will need to create a client application and communicate with the service and/or sub-application via rpc, sockets, or named pipes.
Below is the configuration in Maven software by default in MAVEN_HOME\conf\settings.xml.
<settings>
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ~/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
-->
Add the below line under this configuration, will fulfill the requirement.
<localRepository>custom_path</localRepository>
Ex: <localRepository>D:/MYNAME/settings/.m2/repository</localRepository>
List<WebElement> myElements = driver.findElements(By.xpath("some/path//a"));
System.out.println("Size of List: "+myElements.size());
for(WebElement e : myElements)
{
System.out.print("Text within the Anchor tab"+e.getText()+"\t");
System.out.println("Anchor: "+e.getAttribute("href"));
}
//NOTE: "//a" will give you all the anchors there on after the point your XPATH has reached.
Note that if using the Windows Subsystem for Linux, systemd isn't supported and therefore commands like systemctl
won't work:
Failed to connect to bus: No such file or directory
See Blockers for systemd? #994 on GitHub, Microsoft/WSL.
The mongo server can still be started manual via mondgod
for development of course.
You have to find where the Git executable is and then add the folder to the PATH environment variable in file .bash_profile.
Using terminal:
Search for Git:
sudo find / -name git
Edit the .bash_profile file. Add:
PATH="<Directory of Git>:$PATH"
Git is back :-)
Anyway, I suggest you to install Git using MacPorts. In this way you can easily upgrade your Git instance to the newest release.
Just subtract the string address from what strchr returns:
char *string = "qwerty";
char *e;
int index;
e = strchr(string, 'e');
index = (int)(e - string);
Note that the result is zero based, so in above example it will be 2.
Here is the BSD implementation:
int
strcmp(s1, s2)
register const char *s1, *s2;
{
while (*s1 == *s2++)
if (*s1++ == 0)
return (0);
return (*(const unsigned char *)s1 - *(const unsigned char *)(s2 - 1));
}
Once there is a mismatch between two characters, it just returns the difference between those two characters.
Also be careful how you execute the js on the page. For example if you do something like this:
(function(window, document, undefined){
var foo = document.getElementById("foo");
console.log(foo);
})(window, document, undefined);
This will return null because you'd be calling the document before it was loaded.
Better option..
(function(window, document, undefined){
// code that should be taken care of right away
window.onload = init;
function init(){
// the code to be called when the dom has loaded
// #document has its nodes
}
})(window, document, undefined);
If you don't know how many attributes need to be processed, you can use the variadic argument list token(...
) introduced in PHP 5.6 (see full documentation here).
Syntax:
function <functionName> ([<type> ]...<$paramName>) {}
For example:
function someVariadricFunc(...$arguments) {
foreach ($arguments as $arg) {
// do some stuff with $arg...
}
}
someVariadricFunc(); // an empty array going to be passed
someVariadricFunc('apple'); // provides a one-element array
someVariadricFunc('apple', 'pear', 'orange', 'banana');
As you can see, this token basically turns all parameters to an array, which you can process in any way you like.
Every method, mentioned earlier does looping either internally or externally, so it is not really important how to implement it. Here another example of finding all references of target string
string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Equals(target));
You cannot decrypt this password again but there is another method named "pwdcompare". Here is a example how to use it with SQL syntax:
USE TEMPDB
GO
declare @hash varbinary (255)
CREATE TABLE tempdb..h (id_num int, hash varbinary (255))
SET @hash = pwdencrypt('123') -- encryption
INSERT INTO tempdb..h (id_num,hash) VALUES (1,@hash)
SET @hash = pwdencrypt('123')
INSERT INTO tempdb..h (id_num,hash) VALUES (2,@hash)
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 2
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
INSERT INTO tempdb..h (id_num,hash)
VALUES (3,CONVERT(varbinary (255),
0x01002D60BA07FE612C8DE537DF3BFCFA49CD9968324481C1A8A8FE612C8DE537DF3BFCFA49CD9968324481C1A8A8))
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 3
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
DROP TABLE tempdb..h
GO
I use __dict__
Example:
class MyObj(object):
def __init__(self):
self.name = 'Chuck Norris'
self.phone = '+6661'
obj = MyObj()
print(obj.__dict__)
# Output:
# {'phone': '+6661', 'name': 'Chuck Norris'}
Remove one element from the Slice (this is called 're-slicing'):
package main
import (
"fmt"
)
func RemoveIndex(s []int, index int) []int {
return append(s[:index], s[index+1:]...)
}
func main() {
all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println(all) //[0 1 2 3 4 5 6 7 8 9]
all = RemoveIndex(all, 5)
fmt.Println(all) //[0 1 2 3 4 6 7 8 9]
}
You need to wait until the image is loaded before you draw it. Try this instead:
var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');
make_base();
function make_base()
{
base_image = new Image();
base_image.src = 'img/base.png';
base_image.onload = function(){
context.drawImage(base_image, 0, 0);
}
}
i.e. draw the image in the onload callback of the image.
No, if you are debugging an app without other users use the Build > Build APK(s) menu in Android Studio or execute it in your device/emulator them the debug release apk will install automatically. If you are debugging an app with others use Build > Generate Signed APK... menu. If you want to publish the beta version use the Google Play Store. Your APK(s) will be in app\build\outputs\apk\debug
and app\release
folders.
No.
An ArrayList can be empty (or with nulls as items) an not be null. It would be considered empty. You can check for am empty ArrayList with:
ArrayList arrList = new ArrayList();
if(arrList.isEmpty())
{
// Do something with the empty list here.
}
Or if you want to create a method that checks for an ArrayList with only nulls:
public static Boolean ContainsAllNulls(ArrayList arrList)
{
if(arrList != null)
{
for(object a : arrList)
if(a != null) return false;
}
return true;
}
Usign fs with node.
var fs = require('fs');
try {
var data = fs.readFileSync('file.txt', 'utf8');
console.log(data.toString());
} catch(e) {
console.log('Error:', e.stack);
}
For jQuery (at least version 1.11.2) the following procedure worked for me.
$._data(($0), 'events');
in the 'Console'handler:
value.And it's time to stop re-inventing the wheel and start using vanilla JS events ... :)
If you debug your code using developer tools, you will notice that this
refers to the window object and not the input control. Consider using the passed in id to retrieve the input and check for checked
value.
function doalert(id){
if(document.getElementById(id).checked) {
alert('checked');
}else{
alert('unchecked');
}
}
something like
for (int rows = 0; rows < dataGrid.Rows.Count; rows++)
{
for (int col= 0; col < dataGrid.Rows[rows].Cells.Count; col++)
{
string value = dataGrid.Rows[rows].Cells[col].Value.ToString();
}
}
example without using index
foreach (DataGridViewRow row in dataGrid.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
string value = cell.Value.ToString();
}
}
As per my understanding you want data in dictionary as shown below:
key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3
for this you can use list for each dictionary keys:
case_list = {}
for entry in entries_list:
if key in case_list:
case_list[key1].append(value)
else:
case_list[key1] = [value]
What this function does is it checks if the property exist on this class of any of his child's, and if so it gets the value otherwise it returns null. So now the properties are optional and dynamic.
/**
* check if property is defined on this class or any of it's childes and return it
*
* @param $property
*
* @return bool
*/
private function getIfExist($property)
{
$value = null;
$propertiesArray = get_object_vars($this);
if(array_has($propertiesArray, $property)){
$value = $propertiesArray[$property];
}
return $value;
}
Usage:
const CONFIG_FILE_PATH_PROPERTY = 'configFilePath';
$configFilePath = $this->getIfExist(self::CONFIG_FILE_PATH_PROPERTY);
Swift 2.1.1 below works:
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let v = UIView()
v.backgroundColor = UIColor.RGB(53, 60, 62)
return v
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 80
}
If use self.theTable.tableFooterView = tableFooter
there is a space between last row and tableFooterView
.
This will do it:
my_hash.each_with_object({}) { |(key, value), hash| hash[key] = value.upcase }
As opposed to inject
the advantage is that you are in no need to return the hash again inside the block.
The API Doc are very clear on this.
All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface. Some applications can choose to provide their own specialized implementations, however, Hibernate provides a range of built-in implementations. The shortcut names for the built-in generators are as follows:
increment
generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster.
identity
supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.
sequence
uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int
hilo
uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database.
seqhilo
uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.
uuid
uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length.
guid
uses a database-generated GUID string on MS SQL Server and MySQL.
native
selects identity, sequence or hilo depending upon the capabilities of the underlying database.
assigned
lets the application assign an identifier to the object before save() is called. This is the default strategy if no element is specified.
select
retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value.
foreign
uses the identifier of another associated object. It is usually used in conjunction with a primary key association.
sequence-identity
a specialized sequence generation strategy that utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to return the generated identifier value as part of the insert statement execution. This strategy is only supported on Oracle 10g drivers targeted for JDK 1.4. Comments on these insert statements are disabled due to a bug in the Oracle drivers.
If you are building a simple application with not much concurrent users, you can go for increment, identity, hilo etc.. These are simple to configure and did not need much coding inside the db.
You should choose sequence or guid depending on your database. These are safe and better because the id
generation will happen inside the database.
Update: Recently we had an an issue with idendity where primitive type (int) this was fixed by using warapper type (Integer) instead.
You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:
if (isset($_GET['search'])) {
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT * FROM users WHERE username = '$search'";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($res);
if ($row){
print_r($row); //do whatever you want with found info
}
}
To include an external Javascript file you use the <script>
tag. The src
attribute points to the location of your Javascript file within your web project.
<script src="some.js" type="text/javascript"></script>
JQuery is simply a Javascript file, so if you download a copy of the file you can include it within your page using a script tag. You can also include Jquery from a content distribution network such as the one hosted by Google.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:
.\mydocuments\folder\mybat.bat
.\mydocuments\folder\subfolder\file.txt
And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:
@Echo OFF
REM Do anything with ".\Subfolder\File1.txt"
PUSHD ".\Subfolder"
Type "File1.txt"
Pause&Exit
Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:
@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit
With Python 3 I had this problem:
self.path = 'T:\PythonScripts\Projects\Utilities'
produced this error:
self.path = 'T:\PythonScripts\Projects\Utilities'
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 25-26: truncated \UXXXXXXXX escape
the fix that worked is:
self.path = r'T:\PythonScripts\Projects\Utilities'
It seems the '\U' was producing an error and the 'r' preceding the string turns off the eight-character Unicode escape (for a raw string) which was failing. (This is a bit of an over-simplification, but it works if you don't care about unicode)
Hope this helps someone
prkey whatsthat cash
890 "abb " 32 32
43 "abbz " 2 34
4 "bttu " 1 35
45 "gasstuff " 2 37
545 "gasz " 5 42
80009 "hoo " 9 51
2321 "ibm " 1 52
998 "krk " 2 54
42 "kx-5010 " 2 56
32 "lto " 4 60
543 "mp " 5 65
465 "multipower " 2 67
455 "O.N. " 1 68
7887 "prem " 7 75
434 "puma " 3 78
23 "retractble " 3 81
242 "Trujillo's stuff " 4 85
That's a result of query. Table used as source is the same exept that it has no last column. This column is a moving sum of third one.
Query:
SELECT prkey,whatsthat,cash,SUM(cash) over (order by whatsthat)
FROM public.iuk order by whatsthat,prkey
;
(table goes as public.iuk)
sql version: 2012
It's a little over dbase(1986) level, I don't know why 25+ years has been needed to finish it up.