Instantiate a new ArrayList:
List<String> myList = new ArrayList<String>();
Iterate over your data structure (with a for loop, for instance, more details on your code would help.) and for each element (yourElement):
myList.add(yourElement);
Not as elegant as the regex answers above, but easier to follow for the not-as-savvy among us:
function removeLastInstance(badtext, str) {
var charpos = str.lastIndexOf(badtext);
if (charpos<0) return str;
ptone = str.substring(0,charpos);
pttwo = str.substring(charpos+(badtext.length));
return (ptone+pttwo);
}
I realize this is likely slower and more wasteful than the regex examples, but I think it might be helpful as an illustration of how string manipulations can be done. (It can also be condensed a bit, but again, I wanted each step to be clear.)
We can use below Curl command in Windows Command prompt to send the request.
Use the Curl command below, replace single quote with double quotes, remove quotes where they are not there in below format and use the ^
symbol.
curl http://localhost:7101/module/url ^
-d @D:/request.xml ^
-H "Content-Type: text/xml" ^
-H "SOAPAction: process" ^
-H "Authorization: Basic xyz" ^
-X POST
I finally solved it:
In Visual Studio, create a ContextMenuStrip with an item called "DeleteRow"
Then at the DataGridView link the ContextMenuStrip
Using the code below helped me getting it work.
this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
this.DeleteRow.Click += new System.EventHandler(this.DeleteRow_Click);
Here is the cool part
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
var hti = MyDataGridView.HitTest(e.X, e.Y);
MyDataGridView.ClearSelection();
MyDataGridView.Rows[hti.RowIndex].Selected = true;
}
}
private void DeleteRow_Click(object sender, EventArgs e)
{
Int32 rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
MyDataGridView.Rows.RemoveAt(rowToDelete);
MyDataGridView.ClearSelection();
}
continue
simply skips the rest of the code in the loop until next iteration
You can just use something like this to have two way data binding:
<input type="checkbox" [checked]="model.property" (change)="model.property = !model.consent_obtained_ind">
Materialized views are disk based and are updated periodically based upon the query definition.
Views are virtual only and run the query definition each time they are accessed.
#div:before {
content:"";
position:absolute;
width:100%;
background:#fff;
height:38px;
top:1px;
right:-5px;
}
The DataRow
has also an indexer:
Object cellValue = dt.Rows[i][j];
But i would prefer the strongly typed Field
extension method which also supports nullable types:
int number = dt.Rows[i].Field<int>(j);
or even more readable and less error-prone with the name of the column:
double otherNumber = dt.Rows[i].Field<double>("DoubleColumn");
I had a similar issue and I did this.
Step 1 : Type "regedit" in start menu
Step 2 : Run the registry editor
Step 3 : Navigate to HKEY_CURRENT_USER\SOFTWARE\Classes\Directory\Background\shell
Step 4 : Right-click on "shell" and choose New > Key. name the Key "Bash"
Step 5 : Modify the value and set it to "open in Bash" This is the text that appears in the right click.
Step 6 : Create a new key under Bash and name it "command". Set the value of this key to your git-bash.exe path.
Close the registry editor.
You should now be able to see the option in right click menu in explorer
PS Git Bash by default picks up the current directory.
EDIT : If you want a one click approach, check Ozesh's solution below
If you want to upload a folder or a file to Github
1- Create a repository on the Github
2- make: git remote add origin "Your Link" as it is described on the Github
3- Then use git push -u origin master.
4- You have to enter your username and Password.
5- After the authentication, the transfer will start
This happened to me already twice in a complex WPF app, in it there are 4 multi platform projects, 1 shared project, 2 support libraries, and 1 test project..
This very specific XAML namespace error happened twice on very recently modified files on the Shared project. In both of my cases, it was a new c# file added with a repeating namespace entry;
Like namespace MyProgram.MyFolder.MyProgram.MyFolder
I double pasted it once by mistake, and once it was due to JetBrains Rider double pasting the namespace. (If you ever rename a project in Rider, it time to time starts double pasting namespaces on new file creations, especially on Shared projects..). These c# files with repeating namespaces were then called in the ViewModels where XAML files were referencing to. Well you then get these unrelated and misleading errors, you can have a problem with one file, all your Xaml files will start erroring out eventually.
Anyways, if you get these kind of errors, it's most of the time an issue on a very newly added file or code change. My suggestions would be to look at your very recent changes.
If you want to write a simple toast in your activity:
Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
1.Showing TextView in Toast:---
TextView tv = new TextView(this);
tv.setText("Hello!");
tv.setTextSize(30);
tv.setTextColor(Color.RED);
tv.setBackgroundColor(Color.YELLOW);
2.Showing Image as Toast:--
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.blonde);
Toast t = new Toast(this);
t.setView(iv);
t.setDuration(Toast.LENGTH_LONG);
t.show();
3.showing Layout as Toast:--
LayoutInflater li = getLayoutInflater();
View view = li.inflate(R.layout.my_toast_layout,null,false);
Toast t = new Toast(this);
t.setView(view);
t.setDuration(Toast.LENGTH_LONG);
t.show();
** If you want to write the toast in your Async then:
private Activity activity;
private android.content.Context context;
this.activity = activity;
this.context = context;
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();
If the file that this script lives in is executable, the hash-bang (#!
) tells the operating system what interpreter to use to run the script. In this case it's /bin/sh
, for example.
There's a Wikipedia article about it for more information.
Use Shift + Insert like in linux bash
Edit: It works even in putty.
• Debug: fine-grained statements concerning program state, typically used for debugging;
• Info: informational statements concerning program state, representing program events or behavior tracking;
• Warn: statements that describe potentially harmful events or states in the program;
• Error: statements that describe non-fatal errors in the application; this level is used quite often for logging handled exceptions;
• Fatal: statements representing the most severe of error conditions, assumedly resulting in program termination.
Found on http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx
Simply use below code as follows.
List<String> list = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
Look at the const
and static
section of the Rust book.
You can use something as follows:
const N: i32 = 5;
or
static N: i32 = 5;
in global space.
But these are not mutable. For mutability, you could use something like:
static mut N: i32 = 5;
Then reference them like:
unsafe {
N += 1;
println!("N: {}", N);
}
If you were to inspect the event.target
with firebug or chrome's developer tools you would see for a span element (e.g. the following properties) it will have whatever properties any element has. It depends what the target element is:
event.target: HTMLSpanElement
attributes: NamedNodeMap
baseURI: "file:///C:/Test.html"
childElementCount: 0
childNodes: NodeList[1]
children: HTMLCollection[0]
classList: DOMTokenList
className: ""
clientHeight: 36
clientLeft: 1
clientTop: 1
clientWidth: 1443
contentEditable: "inherit"
dataset: DOMStringMap
dir: ""
draggable: false
firstChild: Text
firstElementChild: null
hidden: false
id: ""
innerHTML: "click"
innerText: "click"
isContentEditable: false
lang: ""
lastChild: Text
lastElementChild: null
localName: "span"
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: null
nextSibling: null
nodeName: "SPAN"
nodeType: 1
nodeValue: null
offsetHeight: 38
offsetLeft: 26
offsetParent: HTMLBodyElement
offsetTop: 62
offsetWidth: 1445
onabort: null
onbeforecopy: null
onbeforecut: null
onbeforepaste: null
onblur: null
onchange: null
onclick: null
oncontextmenu: null
oncopy: null
oncut: null
ondblclick: null
ondrag: null
ondragend: null
ondragenter: null
ondragleave: null
ondragover: null
ondragstart: null
ondrop: null
onerror: null
onfocus: null
oninput: null
oninvalid: null
onkeydown: null
onkeypress: null
onkeyup: null
onload: null
onmousedown: null
onmousemove: null
onmouseout: null
onmouseover: null
onmouseup: null
onmousewheel: null
onpaste: null
onreset: null
onscroll: null
onsearch: null
onselect: null
onselectstart: null
onsubmit: null
onwebkitfullscreenchange: null
outerHTML: "<span>click</span>"
outerText: "click"
ownerDocument: HTMLDocument
parentElement: HTMLElement
parentNode: HTMLElement
prefix: null
previousElementSibling: null
previousSibling: null
scrollHeight: 36
scrollLeft: 0
scrollTop: 0
scrollWidth: 1443
spellcheck: true
style: CSSStyleDeclaration
tabIndex: -1
tagName: "SPAN"
textContent: "click"
title: ""
webkitdropzone: ""
__proto__: HTMLSpanElement
Using Xcode 10.3
Follow these steps:
Account
> Certificates, Identifiers & Profiles
> Devices
Xcode
select your iPhone and Run itDo not forget to go Settings
> General
> Device Management
to trust the developer account
Just to help anyone coming to this page. This is an alternate if you are flexible with using some other icon library.
James is correct that you cannot change the font weight however if you are looking for more modern look for icons then you might consider ionicons
It has both ios and android versions for icons.
Did the error also report that it was missing an application name? I had this issue until I created a project name (e.g. "Project X") in the project settings dialog.
All you have to do is this
list = ["a", "b", "c"]
try:
list.remove("a")
except:
print("meow")
but that method has an issue. You have to put something in the except place so i found this:
list = ["a", "b", "c"]
if "a" in str(list):
list.remove("a")
In order to see the changes that have been staged already, you can pass the -–staged
option to git diff
(in pre-1.6 versions of Git, use –-cached
).
git diff --staged
git diff --cached
add to your qmake file
QMAKE_CXXFLAGS+= -std=c++11
QMAKE_LFLAGS += -std=c++11
I faced the same error when displaying YouTube links.
For example: https://www.youtube.com/watch?v=8WkuChVeL0s
I replaced watch?v=
with embed/
so the valid link will be:
https://www.youtube.com/embed/8WkuChVeL0s
It works well.
Try to apply the same rule on your case.
for example:
<ImageView android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="42dp"
android:maxHeight="42dp"
android:scaleType="fitCenter"
android:layout_marginLeft="3dp"
android:src="@drawable/icon"
/>
Add property android:scaleType="fitCenter"
and android:adjustViewBounds="true"
.
What I do is something just a little bit different from @Chase answer:
var employees = {};
// ...and then:
employees.accounting = new Array();
for (var i = 0; i < someArray.length; i++) {
var temp_item = someArray[i];
// Maybe, here make something like:
// temp_item.name = 'some value'
employees.accounting.push({
"firstName" : temp_item.firstName,
"lastName" : temp_item.lastName,
"age" : temp_item.age
});
}
And that work form me!
I hope it could be useful for some body else!
I have spent a lot of time trying to figure this out, for devices with scaling factor is very difficult to get the actual size of the screen due to the scaling factor sometimes 125% or 150% when the calls are made to the C# objects the returning value is not the right now, so you need to make a windows API call to get the scaling factor and apply the multiplier, the only working way that I have found for non WPF apps is here
@Test
public void emptyJsonParseTest() {
JsonNode emptyJsonNode = new ObjectMapper().createObjectNode();
Assert.assertTrue(emptyJsonNode.asText().isEmpty());
}
If the requirement is to copy all files in "\Publish\Appfolder" into the parent "\Publish\" folder (inclusive of any subfolders, following works for me) The switch '/s' allows copying of all subfolders, recursively.
xcopy src\main\Publish\Appfolder\*.* /s src\main\Publish\
you can run plain cat
without any arguments as mentioned by bro @Sa'ad to simply keep the container working [actually doing nothing but waiting for user input] (Jenkins' Docker plugin does the same thing)
Just for those interested you can avoid writing custom function by passing NULL as last parameter (if you do not intend to do extra processing of returned data).
In this case default internal function is used.
Details
http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTWRITEDATA
Example
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
FILE *fp;
CURLcode res;
char *url = "http://stackoverflow.com";
char outfilename[FILENAME_MAX] = "page.html";
curl = curl_easy_init();
if (curl)
{
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
It turned out that there's a simple, standard way to achieve what I wanted:
import java.net.Authenticator;
import java.net.PasswordAuthentication;
Authenticator myAuth = new Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("german", "german".toCharArray());
}
};
Authenticator.setDefault(myAuth);
No custom "sun" classes or external dependencies, and no manually encode anything.
I'm aware that BASIC security is not, well, secure, but we are also using HTTPS.
Here is my mysql backup script for ubuntu in case it helps someone.
#Mysql back up script
start_time="$(date -u +%s)"
now(){
date +%d-%B-%Y_%H-%M-%S
}
ip(){
/sbin/ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print $2}'|sed 's/addr://'
}
filename="`now`".zip
backupfolder=/path/to/any/folder
fullpathbackupfile=$backupfolder/$filename
db_user=xxx
db_password=xxx
db_name=xxx
printf "\n\n"
printf "******************************\n"
printf "Started Automatic Mysql Backup\n"
printf "******************************\n"
printf "TIME: `now`\n"
printf "IP_ADDRESS: `ip` \n"
printf "DB_SERVER_NAME: DB-SERVER-1\n"
printf "%sBACKUP_FILE_PATH $fullpathbackupfile\n"
printf "Starting Mysql Dump \n"
mysqldump -u $db_user -p$db_password $db_name| pv | zip > $fullpathbackupfile
end_time="$(date -u +%s)"
elapsed=$(($end_time-$start_time))
printf "%sMysql Dump Completed In $elapsed seconds\n"
printf "******************************\n"
PS: Rememember to install pv and zip in your ubuntu
sudo apt install pv
sudo apt install zip
Here is how I set crontab by using crontab -e
in ubuntu to run every 6 hours
0 */6 * * * sh /path/to/shfile/backup-mysql.sh >> /path/to/logs/backup-mysql.log 2>&1
Cool thing is it will create a zip file which is easier to unzip from anywhere
You need to make sure your pandas dataframe columns are appropriate for the type spark is inferring. If your pandas dataframe lists something like:
pd.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5062 entries, 0 to 5061
Data columns (total 51 columns):
SomeCol 5062 non-null object
Col2 5062 non-null object
And you're getting that error try:
df[['SomeCol', 'Col2']] = df[['SomeCol', 'Col2']].astype(str)
Now, make sure .astype(str)
is actually the type you want those columns to be. Basically, when the underlying Java code tries to infer the type from an object in python it uses some observations and makes a guess, if that guess doesn't apply to all the data in the column(s) it's trying to convert from pandas to spark it will fail.
As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:
xlrd has explicitly removed support for anything other than xls files.
In your case, the solution is to:
openpyxl
: https://openpyxl.readthedocs.io/en/stable/df1 = pd.read_excel(
os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
engine='openpyxl',
)
first, check that who uses port 8080.
if the port 8080 is in use, change the listening port to 8181.
if you use IDEA, modify start configuration, Run-> Edit Configuration enter image description here
if you use mvn spring-boot, then use the command:
mvn spring-boot:run -Dserver.port=8181
if you use java -jar, then use the command:
java -jar xxxx.jar --server.port=8181
The functions getElementById
and getElementsByClassName
are very specific, while querySelector
and querySelectorAll
are more elaborate. My guess is that they will actually have a worse performance.
Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".
function function_one() {
function_two();
}
function function_two() {
//enter code here
}
For Python version 2.7 @Anthony solution works perfect, by changing python3 to python as follows:
sudo python -m pip uninstall pip && sudo apt install python-pip --reinstall
@thamme-gowda's solution works for images too!
| |
|:----------------------------------------------------------------------------:|
| ![](https://gravatar.com/avatar/4cc702785290b4934c531c56f6061e5e "Tonejito") |
You can check this out on a gist I made for that. Here is a render of the table hack on GitHub and GitLab:
Don't do this! Really, not a good idea.
If you know which tables you want to truncate, create a stored procedure which truncates them. You can fix the order to avoid foreign key problems.
If you really want to truncate them all (so you can BCP load them for example) you would be just as quick to drop the database and create a new one from scratch, which would have the additional benefit that you know exactly where you are.
While the accepted answer will work most of the times, I have encountered (still do not know why) some cases that is does not. A slight modification of the query by using the WITH OVERRIDE
in RECONFIGURE
gives the solution
Use Master
GO
EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO
EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE WITH OVERRIDE
GO
The expected output is
Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.
Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.
Also do note when specifying DATETIME
as DATETIME(3)
or like on MySQL 5.7.x, you also have to add the same value for CURRENT_TIMESTAMP(3)
. If not it will keep throwing 'Invalid default value'.
In case you want a nice no dependencies copy-paste solution. Grab the code below.
MyObject myObject = ...
byte[] bytes = SerializeUtils.serialize(myObject);
myObject = SerializeUtils.deserialize(bytes);
import java.io.*;
public class SerializeUtils {
public static byte[] serialize(Serializable value) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try(ObjectOutputStream outputStream = new ObjectOutputStream(out)) {
outputStream.writeObject(value);
}
return out.toByteArray();
}
public static <T extends Serializable> T deserialize(byte[] data) throws IOException, ClassNotFoundException {
try(ByteArrayInputStream bis = new ByteArrayInputStream(data)) {
//noinspection unchecked
return (T) new ObjectInputStream(bis).readObject();
}
}
}
Make sure you do not use the trailing semicolon: This will not work:
set JAVA_HOME=C:\Program Files (x86)\Java\jdk1.6.0_29;
This will:
set JAVA_HOME=C:\Program Files (x86)\Java\jdk1.6.0_29
For small scripts an optional way to make it readable is to use a variable like this:
awk -v fmt="'%s'\n" '{printf fmt, $1}'
I found it conveninet in a case where I had to produce many times the single-quote character in the output and the \047 were making it totally unreadable
You will have to use a setTimeout so I see your issue as
I have a script that is generated by PHP, and so am not able to put it into two different functions
What prevents you from generating two functions in your script?
function fizz() {
var a;
a = 'buzz';
// sleep x desired
a = 'complete';
}
Could be rewritten as
function foo() {
var a; // variable raised so shared across functions below
function bar() { // consider this to be start of fizz
a = 'buzz';
setTimeout(baz, x); // start wait
} // code split here for timeout break
function baz() { // after wait
a = 'complete';
} // end of fizz
bar(); // start it
}
You'll notice that a
inside baz
starts as buzz
when it is invoked and at the end of invocation, a
inside foo
will be "complete"
.
Basically, wrap everything in a function, move all variables up into that wrapping function such that the contained functions inherit them. Then, every time you encounter wait NUMBER seconds
you echo
a setTimeout
, end the function and start a new function to pick up where you left off.
I would rather create a function like TryParse or use T-SQL TRY-CATCH
block to get what you wanted.
ISNUMERIC doesn't always work as intended. The code given before will fail if you do:
SET @text = '$'
$ sign can be converted to money datatype, so ISNUMERIC()
returns true in that case. It will do the same for '-' (minus), ',' (comma) and '.' characters.
My simple, simple, simple approach! =D
Code
string_to_test = "The criminals stole $1,000,000 in jewels."
chars_to_check = ["$", ",", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for char in chars_to_check:
if char in string_to_test:
print("Char \"" + char + "\" detected!")
Output
Char "$" detected!
Char "," detected!
Char "0" detected!
Char "1" detected!
Thanks!
This can be done with java reflection,This method returns false if any one attribute value is present for the object ,hope it helps some one
public boolean isEmpty() {
for (Field field : this.getClass().getDeclaredFields()) {
try {
field.setAccessible(true);
if (field.get(this)!=null) {
return false;
}
} catch (Exception e) {
System.out.println("Exception occured in processing");
}
}
return true;
}
according to this snippet i use this code and it's working fine:
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
namespace CompressString
{
internal static class StringCompressor
{
/// <summary>
/// Compresses the string.
/// </summary>
/// <param name="text">The text.</param>
/// <returns></returns>
public static string CompressString(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
var memoryStream = new MemoryStream();
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
{
gZipStream.Write(buffer, 0, buffer.Length);
}
memoryStream.Position = 0;
var compressedData = new byte[memoryStream.Length];
memoryStream.Read(compressedData, 0, compressedData.Length);
var gZipBuffer = new byte[compressedData.Length + 4];
Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
return Convert.ToBase64String(gZipBuffer);
}
/// <summary>
/// Decompresses the string.
/// </summary>
/// <param name="compressedText">The compressed text.</param>
/// <returns></returns>
public static string DecompressString(string compressedText)
{
byte[] gZipBuffer = Convert.FromBase64String(compressedText);
using (var memoryStream = new MemoryStream())
{
int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);
var buffer = new byte[dataLength];
memoryStream.Position = 0;
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
gZipStream.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
}
}
Might be late to the party - also, this answer is for LAMP users who got to this thread from google, like me.
Basically, the problem is PMA is trying to connect to SQL with a user that doesn't exist.
At /etc/phpmyadmin/config-db.php, you will find 2 variables: $dbuser, and $dbpass. Those specify the MySQL user and Password that PMA is trying to connect with.
Now, connect with some username/password that work (or just "root" if you are connecting from localhost), create a new user with global priviliges (e.g - %PMA User% with password %Some Random Password%), then in the above mentioned file set:
$dbuser = %PMA User% ;
$dbpass = %Some Random Password%;
You might also change other stuff there, like the server address ($dbserver), the port ($dbport, which might not be the default one on your machine), and more.
And yet another option which consist in reading the CSV file using Pandas and then importing the Pandas DataFrame into Spark.
For example:
from pyspark import SparkContext
from pyspark.sql import SQLContext
import pandas as pd
sc = SparkContext('local','example') # if using locally
sql_sc = SQLContext(sc)
pandas_df = pd.read_csv('file.csv') # assuming the file contains a header
# pandas_df = pd.read_csv('file.csv', names = ['column 1','column 2']) # if no header
s_df = sql_sc.createDataFrame(pandas_df)
I found an excellent page with information on collision detection and response in 2D.
http://www.metanetsoftware.com/technique.html (web.archive.org)
They try to explain how it's done from an academic point of view. They start with the simple object-to-object collision detection, and move on to collision response and how to scale it up.
Edit: Updated link
I have a slightly different solution based on the answer by user167517. In my function I'm using a variable for the id of the select box I'm targeting.
var vOptionSelect = "#productcodeSelect1";
The index is returned with:
$(vOptionSelect).find(":selected").index();
Steps:
After all it works for me and hopefully work for you.
because you are just learning I suggest you practice converting a SELECT joins to UPDATE or DELETE joins. First I suggest you generate a SELECT statement joining these two tables:
SELECT *
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
Then note that we have two table aliases a
and b
. Using these aliases you can easily generate UPDATE statement to update either table a or b. For table a you have an answer provided by JW. If you want to update b
, the statement will be:
UPDATE b
SET b.marks = a.marks
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
Now, to convert the statement to a DELETE statement use the same approach. The statement below will delete from a
only (leaving b intact) for those records that match by name:
DELETE a
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
You can use the SQL Fiddle created by JW as a playground
That's probably a requireJS module definition
Check here for more details
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
A new service called "Web Deployment Agent Service" (MsDepSvc) can also trigger "System" with PID=4 to listen on port 80.
You found one answer, i.e. eval(parse())
. You can also investigate do.call()
which is often simpler to implement. Keep in mind the useful as.name()
tool as well, for converting strings to variable names.
I don't think they are reprinting paper books each year. The copyright of the year when the book was printed is valid in all next years.
The same principle should apply to web pages, too. However "the year when website was created" is a bit different. So, if you make changes to your web site - you are not done yet. Hence, when updating the site, you may want to update the copyright year.
By adb shell input keyevent
, either an event_code
or a string
will be sent to the device.
usage: input [text|keyevent]
input text <string>
input keyevent <event_code>
Some possible values for event_code
are:
0 --> "KEYCODE_UNKNOWN"
1 --> "KEYCODE_MENU"
2 --> "KEYCODE_SOFT_RIGHT"
3 --> "KEYCODE_HOME"
4 --> "KEYCODE_BACK"
5 --> "KEYCODE_CALL"
6 --> "KEYCODE_ENDCALL"
7 --> "KEYCODE_0"
8 --> "KEYCODE_1"
9 --> "KEYCODE_2"
10 --> "KEYCODE_3"
11 --> "KEYCODE_4"
12 --> "KEYCODE_5"
13 --> "KEYCODE_6"
14 --> "KEYCODE_7"
15 --> "KEYCODE_8"
16 --> "KEYCODE_9"
17 --> "KEYCODE_STAR"
18 --> "KEYCODE_POUND"
19 --> "KEYCODE_DPAD_UP"
20 --> "KEYCODE_DPAD_DOWN"
21 --> "KEYCODE_DPAD_LEFT"
22 --> "KEYCODE_DPAD_RIGHT"
23 --> "KEYCODE_DPAD_CENTER"
24 --> "KEYCODE_VOLUME_UP"
25 --> "KEYCODE_VOLUME_DOWN"
26 --> "KEYCODE_POWER"
27 --> "KEYCODE_CAMERA"
28 --> "KEYCODE_CLEAR"
29 --> "KEYCODE_A"
30 --> "KEYCODE_B"
31 --> "KEYCODE_C"
32 --> "KEYCODE_D"
33 --> "KEYCODE_E"
34 --> "KEYCODE_F"
35 --> "KEYCODE_G"
36 --> "KEYCODE_H"
37 --> "KEYCODE_I"
38 --> "KEYCODE_J"
39 --> "KEYCODE_K"
40 --> "KEYCODE_L"
41 --> "KEYCODE_M"
42 --> "KEYCODE_N"
43 --> "KEYCODE_O"
44 --> "KEYCODE_P"
45 --> "KEYCODE_Q"
46 --> "KEYCODE_R"
47 --> "KEYCODE_S"
48 --> "KEYCODE_T"
49 --> "KEYCODE_U"
50 --> "KEYCODE_V"
51 --> "KEYCODE_W"
52 --> "KEYCODE_X"
53 --> "KEYCODE_Y"
54 --> "KEYCODE_Z"
55 --> "KEYCODE_COMMA"
56 --> "KEYCODE_PERIOD"
57 --> "KEYCODE_ALT_LEFT"
58 --> "KEYCODE_ALT_RIGHT"
59 --> "KEYCODE_SHIFT_LEFT"
60 --> "KEYCODE_SHIFT_RIGHT"
61 --> "KEYCODE_TAB"
62 --> "KEYCODE_SPACE"
63 --> "KEYCODE_SYM"
64 --> "KEYCODE_EXPLORER"
65 --> "KEYCODE_ENVELOPE"
66 --> "KEYCODE_ENTER"
67 --> "KEYCODE_DEL"
68 --> "KEYCODE_GRAVE"
69 --> "KEYCODE_MINUS"
70 --> "KEYCODE_EQUALS"
71 --> "KEYCODE_LEFT_BRACKET"
72 --> "KEYCODE_RIGHT_BRACKET"
73 --> "KEYCODE_BACKSLASH"
74 --> "KEYCODE_SEMICOLON"
75 --> "KEYCODE_APOSTROPHE"
76 --> "KEYCODE_SLASH"
77 --> "KEYCODE_AT"
78 --> "KEYCODE_NUM"
79 --> "KEYCODE_HEADSETHOOK"
80 --> "KEYCODE_FOCUS"
81 --> "KEYCODE_PLUS"
82 --> "KEYCODE_MENU"
83 --> "KEYCODE_NOTIFICATION"
84 --> "KEYCODE_SEARCH"
85 --> "TAG_LAST_KEYCODE"
The sendevent
utility sends touch or keyboard events, as well as other events for simulating the hardware events. Refer to this article for details: Android, low level shell click on screen.
Yes! exit()
. It's in <cstdlib>
.
Use a comma to specify two (or more) different rules:
@media screen and (max-width: 995px),
screen and (max-height: 700px) {
...
}
From https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
Commas are used to combine multiple media queries into a single rule. Each query in a comma-separated list is treated separately from the others. Thus, if any of the queries in a list is true, the entire media statement returns true. In other words, lists behave like a logical or operator.
Note that -regex
depends on whole path.
-regex pattern
File name matches regular expression pattern.
This is a match on the whole path, not a search.
You don't actually have to use -regex
for what you are doing.
find . -iname "*[0-9]"
Use TOP 1
if the query returns multiple rows.
SELECT TOP 1 @ModelID = m.modelid
FROM MODELS m
WHERE m.areaid = 'South Coast'
In case it is an Android gradle project - you can find the android libraries below your $ANDROID_HOME/extras/android/m2repository folder
Let's understand in simple words
Note: These keys have more depth as a concept but this is good to start.
from subprocess import call
def cp_dir(source, target):
call(['cp', '-a', source, target]) # Linux
cp_dir('/a/b/c/', '/x/y/z/')
It works for me. Basically, it executes shell command cp.
How about a solution where you put the actual "data" of the table inside its own div, with overflow: scroll;
? Then the browser will automatically create scrollbars for the portion of the "table" you do not want to lock, and you can put the "table header"/first row just above that <div>
.
Not sure how that would work with scrolling horizontally though.
ldapwhoami -vvv -h <hostname> -p <port> -D <binddn> -x -w <passwd>
, where binddn
is the DN of the person whose credentials you are authenticating.
On success (i.e., valid credentials), you get Result: Success (0)
. On failure, you get ldap_bind: Invalid credentials (49)
.
In addition to registering a ByteArrayHttpMessageConverter
, you may want to use a ResponseEntity
instead of @ResponseBody
. The following code works for me :
@RequestMapping("/photo2")
public ResponseEntity<byte[]> testphoto() throws IOException {
InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
}
use the grid-system of boostrap , more information here
for example
<div class="row">
<div class="col-md-4">here img</div>
<div class="col-md-4">here text</div>
</div>
in this way when the page will shrink the second div(the text) will be found under the first(the image)
create toggle_selector.xml in res/drawable
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/toggle_on" android:state_checked="true"/>
<item android:drawable="@drawable/toggle_off" android:state_checked="false"/>
</selector>
apply the selector to your toggle button
<ToggleButton
android:id="@+id/chkState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/toggle_selector"
android:textOff=""
android:textOn=""/>
Note: for removing the text i used following in above code
textOff=""
textOn=""
You don't need to convert it at all:
% perl -e 'print "5.45" + 0.1;'
5.55
I found one way to access the shared folder without giving the username and password.
We need to change the share folder protect settings in the machine where the folder has been shared.
Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.
By doing the above settings we can access the shared folder without any username/password.
If you are trying to open a file in the same directory it would be:
./PROGRAM TRYING TO OPEN
./FILE NAME/PROGRAM TRYING TO OPEN (or this)
Or, if trying to backtrack from the same directory it would be:
../PROGRAM TRYING TO OPEN
../FILE NAME/PROGRAM TRYING TO OPEN (or this)
Else, if you need a straight one from start, it would be:
(DIRECTORY TYPE)\Users\%username%\(FILE DIRECTORY)
(ex) C:\Users\ajste\Desktop\Henlo.cmd
clang++ 3.5 even warns on it:
/tmp/a.C:3:7: warning: reference cannot be bound to dereferenced null pointer in well-defined C++ code; comparison may be assumed to
always evaluate to false [-Wtautological-undefined-compare]
if( & nullReference == 0 ) // null reference
^~~~~~~~~~~~~ ~
1 warning generated.
Just add !
before an exclusion rule.
According to the gitignore man page:
Patterns have the following format:
...
- An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
You can set it as a no title bar theme in the activity's xml in the AndroidManifest
<activity
android:name=".AnActivity"
android:label="@string/a_string"
android:theme="@android:style/Theme.NoTitleBar">
</activity>
File myFile=new File("/tmp/myfile");
URL myUrl = myFile.toURI().toURL();
These answers are all way too complicated!
The way he wrote the method is fine. The problem is where he invoked the method. He did not include parentheses after the method name, so the compiler thought he was trying to get a value from a variable instead of a method.
In Visual Basic and Delphi, those parentheses are optional, but in C#, they are required. So, to correct the last line of the original post:
Console.WriteLine("{0}", x.fullNameMethod());
INSERT INTO vendors (
name,
phone,
addressLine1,
addressLine2,
city,
state,
postalCode,
country,
customer_id
)
SELECT
name,
phone,
addressLine1,
addressLine2,
city,
state ,
postalCode,
country,
customer_id
FROM
customers;
For upgrade code retrieval: How can I find the Upgrade Code for an installed MSI file?
The information below has grown considerably over time and may have become a little too elaborate. How to get product codes quickly? (four approaches):
Use the Powershell "one-liner"
Scroll down for screenshot and step-by-step. Disclaimer also below - minor or moderate risks depending on who you ask. Works OK for me. Any self-repair triggered by this option should generally be possible to cancel. The package integrity checks triggered does add some event log "noise" though. Note! IdentifyingNumber
is the ProductCode
(WMI peculiarity).
get-wmiobject Win32_Product | Sort-Object -Property Name |Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize
Quick start of Powershell: hold Windows key, tap R, type in "powershell" and press Enter
Use VBScript
(script on github.com)Described below under "Alternative Tools" (section 3). This option may be safer than Powershell for reasons explained in detail below. In essence it is (much) faster and not capable of triggering MSI self-repair since it does not go through WMI (it accesses the MSI COM API directly - at blistering speed). However, it is more involved than the Powershell option (several lines of code).
Registry Lookup
Some swear by looking things up in the registry. Not my recommended approach - I like going through proper APIs (or in other words: OS function calls). There are always weird exceptions accounted for only by the internals of the API-implementation:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall
HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall
Original MSI File / WiX Source
You can find the Product Code
in the Property table
of any MSI file (and any other property as well). However, the GUID could conceivably (rarely) be overridden by a transform applied at install time and hence not match the GUID the product is registered under (approach 1 and 2 above will report the real product code - that is registered with Windows - in such rare scenarios).
You need a tool to view MSI files. See towards the bottom of the following answer for a list of free tools you can download (or see quick option below): How can I compare the content of two (or more) MSI files?
UPDATE: For convenience and need for speed :-), download SuperOrca without delay and fuss from this direct-download hotlink - the tool is good enough to get the job done - install, open MSI and go straight to the Property table and find the ProductCode
row (please always virus check a direct-download hotlink - obviously - you can use virustotal.com to do so - online scan utilizing dozens of anti-virus and malware suites to scan what you upload).
Orca is Microsoft's own tool, it is installed with Visual Studio and the Windows SDK. Try searching for
Orca-x86_en-us.msi
- underProgram Files (x86)
and install the MSI if found.
- Current path:
C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\x86
- Change version numbers as appropriate
And below you will find the original answer which "organically grew" into a lot of detail.
Maybe see "Uninstall MSI Packages" section below if this is the task you need to perform.
UPDATE: If you also need the upgrade code, check this answer: How can I find the Upgrade Code for an installed MSI file? (retrieves associated product codes, upgrade codes & product names in a table output - similar to the one below).
- Can't use PowerShell? See "Alternative Tools" section below.
- Looking to uninstall? See "Uninstall MSI packages" section below.
Fire up Powershell (hold down the Windows key, tap R, release the Windows key, type in "powershell" and press OK) and run the command below to get a list of installed MSI package product codes along with the local cache package path and the product name (maximize the PowerShell window to avoid truncated names).
Before running this command line, please read the disclaimer below (nothing dangerous, just some potential nuisances). Section 3 under "Alternative Tools" shows an alternative non-WMI way to get the same information using VBScript. If you are trying to uninstall a package there is a section below with some sample msiexec.exe command lines:
get-wmiobject Win32_Product | Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize
The output should be similar to this:
Note! For some strange reason the "ProductCode" is referred to as "IdentifyingNumber" in WMI. So in other words - in the picture above the IdentifyingNumber is the ProductCode.
If you need to run this query remotely against lots of remote computer, see "Retrieve Product Codes From A Remote Computer" section below.
DISCLAIMER (important, please read before running the command!): Due to strange Microsoft design, any WMI call to
Win32_Product
(like the PowerShell command below) will trigger a validation of the package estate. Besides being quite slow, this can in rare cases trigger an MSI self-repair. This can be a small package or something huge - like Visual Studio. In most cases this does not happen - but there is a risk. Don't run this command right before an important meeting - it is not ever dangerous (it is read-only), but it might lead to a long repair in very rare cases (I think you can cancel the self-repair as well - unless actively prevented by the package in question, but it will restart if you call Win32_Product again and this will persist until you let the self-repair finish - sometimes it might continue even if you do let it finish: How can I determine what causes repeated Windows Installer self-repair?).And just for the record: some people report their event logs filling up with MsiInstaller EventID 1035 entries (see code chief's answer) - apparently caused by WMI queries to the Win32_Product class (personally I have never seen this). This is not directly related to the Powershell command suggested above, it is in context of general use of the WIM class Win32_Product.
You can also get the output in list form (instead of table):
get-wmiobject -class Win32_Product
In this case the output is similar to this:
In theory you should just be able to specify a remote computer name as part of the command itself. Here is the same command as above set up to run on the machine "RemoteMachine" (-ComputerName RemoteMachine
section added):
get-wmiobject Win32_Product -ComputerName RemoteMachine | Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize
This might work if you are running with domain admin rights on a proper domain. In a workgroup environment (small office / home network), you probably have to add user credentials directly to the WMI calls to make it work.
Additionally, remote connections in WMI are affected by (at least) the Windows Firewall, DCOM settings, and User Account Control (UAC) (plus any additional non-Microsoft factors - for instance real firewalls, third party software firewalls, security software of various kinds, etc...). Whether it will work or not depends on your exact setup.
UPDATE: An extensive section on remote WMI running can be found in this answer: How can I find the Upgrade Code for an installed MSI file?. It appears a firewall rule and suppression of the UAC prompt via a registry tweak can make things work in a workgroup network environment. Not recommended changes security-wise, but it worked for me.
PowerShell requires the .NET framework to be installed (currently in version 3.5.1 it seems? October, 2017). The actual PowerShell application itself can also be missing from the machine even if .NET is installed. Finally I believe PowerShell can be disabled or locked by various system policies and privileges.
If this is the case, you can try a few other ways to retrieve product codes. My preferred alternative is VBScript - it is fast and flexible (but can also be locked on certain machines, and scripting is always a little more involved than using tools).
wbemtest.exe
.wbemtest.exe
(Hold down the Windows key, tap R, release the Windows key, type in "wbemtest.exe" and press OK).SELECT IdentifyingNumber,Name,Version FROM Win32_Product
and click "Use" (or equivalent - the tool will be localized).WMIExplorer.exe
SELECT IdentifyingNumber,Name,Version FROM Win32_Product
and press Execute.msiinfo.csv
.' Retrieve all ProductCodes (with ProductName and ProductVersion)
Set fso = CreateObject("Scripting.FileSystemObject")
Set output = fso.CreateTextFile("msiinfo.csv", True, True)
Set installer = CreateObject("WindowsInstaller.Installer")
On Error Resume Next ' we ignore all errors
For Each product In installer.ProductsEx("", "", 7)
productcode = product.ProductCode
name = product.InstallProperty("ProductName")
version=product.InstallProperty("VersionString")
output.writeline (productcode & ", " & name & ", " & version)
Next
output.Close
I can't think of any further general purpose options to retrieve product codes at the moment, please add if you know of any. Just edit inline rather than adding too many comments please.
You can certainly access this information from within your application by calling the MSI automation interface (COM based) OR the C++ MSI installer functions (Win32 API). Or even use WMI queries from within your application like you do in the samples above using
PowerShell
,wbemtest.exe
orWMIExplorer.exe
.
If what you want to do is to uninstall the MSI package you found the product code for, you can do this as follows using an elevated command prompt (search for cmd.exe, right click and run as admin):
Option 1: Basic, interactive uninstall without logging (quick and easy):
msiexec.exe /x {00000000-0000-0000-0000-00000000000C}
Quick Parameter Explanation:
/X = run uninstall sequence
{00000000-0000-0000-0000-00000000000C} = product code for product to uninstall
You can also enable (verbose) logging and run in silent mode if you want to, leading us to option 2:
Option 2: Silent uninstall with verbose logging (better for batch files):
msiexec.exe /x {00000000-0000-0000-0000-00000000000C} /QN /L*V "C:\My.log" REBOOT=ReallySuppress
Quick Parameter Explanation:
/X = run uninstall sequence
{00000000-0000-0000-0000-00000000000C} = product code for product to uninstall
/QN = run completely silently
/L*V "C:\My.log"= verbose logging at specified path
REBOOT=ReallySuppress = avoid unexpected, sudden reboot
There is a comprehensive reference for MSI uninstall here (various different ways to uninstall MSI packages): Uninstalling an MSI file from the command line without using msiexec. There is a plethora of different ways to uninstall.
If you are writing a batch file, please have a look at section 3 in the above, linked answer for a few common and standard uninstall command line variants.
And a quick link to msiexec.exe (command line options) (overview of the command line for msiexec.exe from MSDN). And the Technet version as well.
UPDATE: please find a new answer on how to find the upgrade code for installed packages instead of manually looking up the code in MSI files. For installed packages this is much more reliable. If the package is not installed, you still need to look in the MSI file (or the source file used to compile the MSI) to find the upgrade code. Leaving in older section below:
If you want to get the UpgradeCode or other MSI properties, you can open the cached installation MSI for the product from the location specified by "LocalPackage" in the image show above (something like: C:\WINDOWS\Installer\50c080ae.msi
- it is a hex file name, unique on each system). Then you look in the "Property table" for UpgradeCode (it is possible for the UpgradeCode to be redefined in a transform - to be sure you get the right value you need to retrieve the code programatically from the system - I will provide a script for this shortly. However, the UpgradeCode found in the cached MSI is generally correct).
To open the cached MSI files, use Orca or another packaging tool. Here is a discussion of different tools (any of them will do): What installation product to use? InstallShield, WiX, Wise, Advanced Installer, etc. If you don't have such a tool installed, your fastest bet might be to try Super Orca (it is simple to use, but not extensively tested by me).
UPDATE: here is a new answer with information on various free products you can use to view MSI files: How can I compare the content of two (or more) MSI files?
If you have Visual Studio installed, try searching for Orca-x86_en-us.msi
- under Program Files (x86)
- and install it (this is Microsoft's own, official MSI viewer and editor). Then find Orca in the start menu. Go time in no time :-). Technically Orca is installed as part of Windows SDK (not Visual Studio), but Windows SDK is bundled with the Visual Studio install. If you don't have Visual Studio installed, perhaps you know someone who does? Just have them search for this MSI and send you (it is a tiny half mb file) - should take them seconds. UPDATE: you need several CAB files as well as the MSI - these are found in the same folder where the MSI is found. If not, you can always download the Windows SDK (it is free, but it is big - and everything you install will slow down your PC). I am not sure which part of the SDK installs the Orca MSI. If you do, please just edit and add details here.
Similar topics (for reference and easy access - I should clean this list up):
If you need the hash parameters present in the URL, window.location.href
may be a better choice.
window.location.pathname
=> /search
window.location.href
=> www.website.com/search#race_type=1
You cannot create a backup from a remote server to a local disk - there is just no way to do this. And there are no third-party tools to do this either, as far as I know.
All you can do is create a backup on the remote server machine, and have someone zip it up and send it to you.
It should be noted that the documentation recommends using a Layout
rather than Canvas.drawText
directly. My full answer about using a StaticLayout
is here, but I will provide a summary below.
String text = "This is some text.";
TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);
int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);
Here is a fuller example in the context of a custom view:
public class MyView extends View {
String mText = "This is some text.";
TextPaint mTextPaint;
StaticLayout mStaticLayout;
// use this constructor if creating MyView programmatically
public MyView(Context context) {
super(context);
initLabelView();
}
// this constructor is used when created from xml
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
initLabelView();
}
private void initLabelView() {
mTextPaint = new TextPaint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
mTextPaint.setColor(0xFF000000);
// default to a single line of text
int width = (int) mTextPaint.measureText(mText);
mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
// New API alternate
//
// StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
// .setAlignment(Layout.Alignment.ALIGN_NORMAL)
// .setLineSpacing(1, 0) // multiplier, add
// .setIncludePad(false);
// mStaticLayout = builder.build();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Tell the parent layout how big this view would like to be
// but still respect any requirements (measure specs) that are passed down.
// determine the width
int width;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY) {
width = widthRequirement;
} else {
width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
if (widthMode == MeasureSpec.AT_MOST) {
if (width > widthRequirement) {
width = widthRequirement;
// too long for a single line so relayout as multiline
mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
}
}
}
// determine the height
int height;
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
if (heightMode == MeasureSpec.EXACTLY) {
height = heightRequirement;
} else {
height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(height, heightRequirement);
}
}
// Required call: set width and height
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// do as little as possible inside onDraw to improve performance
// draw the text on the canvas after adjusting for padding
canvas.save();
canvas.translate(getPaddingLeft(), getPaddingTop());
mStaticLayout.draw(canvas);
canvas.restore();
}
}
Here is a one liner implementation using Java8 streams:
String input = "Thequickbrownfoxjumps";
final AtomicInteger atomicInteger = new AtomicInteger(0);
Collection<String> result = input.chars()
.mapToObj(c -> String.valueOf((char)c) )
.collect(Collectors.groupingBy(c -> atomicInteger.getAndIncrement() / 4
,Collectors.joining()))
.values();
It gives the following output:
[Theq, uick, brow, nfox, jump, s]
=Sumifs(B:B,A:A,">=1/1/2013",A:A,"<=1/31/2013")
The beauty of this formula is you can add more data to columns A and B and it will just recalculate.
Do you have to use @Test(expected=SomeException.class)
? When we have to assert the actual message of the exception, this is what we do.
@Test
public void myTestMethod()
{
try
{
final Integer employeeId = null;
new Employee(employeeId);
fail("Should have thrown SomeException but did not!");
}
catch( final SomeException e )
{
final String msg = "Employee ID is null";
assertEquals(msg, e.getMessage());
}
}
Editing hostconfig.json seems to not working now. It only ends with that port being exposed but not published to host. Commiting and recreating containers is not the best approach to me. No one mentioned docker network
?
The best solution would be using reversed proxy within the same network
Create a new network if your previous container not in any named ones.
docker network create my_network
Join your existing container to the created network
docker network connect my_network my_existing_container
Start a reversed proxy service(e.g. nginx) publishing the ports you need, joining the same network
docker run -d --name nginx --network my_network -p 9000:9000 nginx
Optionally remove the default.conf in nginx
docker exec nginx rm /etc/nginx/conf.d/default.conf
Create a new nginx config
server
{
listen 9000;
location / {
proxy_pass http://my_existing_container:9000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Copy the config to nginx container.
docker cp ./my_conf.conf nginx:/etc/nginx/conf.d/my_conf.conf
Restart nginx
docker restart nginx
Advantages: To publish new ports, you can safely stop/update/recreate nginx container as you wish without touching the business container. If you need zero down time for nginx, it is possible to add more reversed proxy services joining the same network. Besides, a container can join more than one network.
Edit:
To reverse proxy non-http services, the config file is a bit different. Here is a simple example:
upstream my_service {
server my_existing_container:9000;
}
server {
listen 9000;
proxy_pass my_service;
}
You can use URL Encoding Functions PHP has the
rawurlencode()
function
ASP has the
Server.URLEncode()
function
In JavaScript you can use the
encodeURIComponent()
function.
Use the in
keyword.
if 'apples' in d:
if d['apples'] == 20:
print('20 apples')
else:
print('Not 20 apples')
If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get
function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None
instead):
if d.get('apples', 0) == 20:
print('20 apples.')
else:
print('Not 20 apples.')
If you use the JSON Serializer, you can simply store your object in string format as such
myHiddenText.value = JSON.stringify( myObject );
You can then get the value back with
myObject = JSON.parse( myHiddenText.value );
However, if you're not going to pass this value across page submits, it might be easier for you, and you'll save yourself a lot of serialization, if you just tuck it away as a global javascript variable.
For me this is the simplest way:
switch (["afshin","saeed","larry"].includes(varName) ? 1 : 2) {
case 1:
alert('Hey');
break;
default:
alert('Default case');
break;
}
I was able to Do it using the U (Underline Tag)
u {
text-decoration: none;
position: relative;
}
u:after {
content: '';
width: 100%;
position: absolute;
left: 0;
bottom: 1px;
border-width: 0 0 1px;
border-style: solid;
}
<a href="" style="text-decoration:none">
<div style="text-align: right; color: Red;">
<u> Shop Now</u>
</div>
</a>
You can put an apostrophe in a single quoted JavaScript string by escaping it with a backslash, like so:
theAnchorText = 'I\'m home';
Note: This is a proper answer for a legacy version of AngularJS. See this question for updated versions.
$scope.$on('$routeChangeStart', function($event, next, current) {
// ... you could trigger something here ...
});
The following events are also available (their callback functions take different arguments):
See the $route docs.
There are two other undocumented events:
See What's the difference between $locationChangeSuccess and $locationChangeStart?
move c:\Sourcefoldernam\*.* e:\destinationFolder
^ This did not work for me for some reason
But when I tried using quotation marks, it suddenly worked:
move "c:\Sourcefoldernam\*.*" "e:\destinationFolder"
I think its because my directory had spaces in one of the folders. So if it doesn't work for you, try with quotation marks!
You can use:
start "windowTitle" fullPath/file.exe
Note: the first set of quotes must be there but you don't have to put anything in them, e.g.:
start "" fullPath/file.exe
You can try using AppDomain.UnhandledException and see if that lets you catch it.
**EDIT*
Here is some more information that might be useful (it's a long read).
Adding screen shots(examples) and some more context for the answer of @Thomas G.
import pandas as pd
is ran properly before checking below shortcut.Place the cursor in middle of parenthesis ()
before you use shortcut.
shift + tab
Display short document and few params
shift + tab + tab
Expands document with scroll bar
shift + tab + tab + tab
Provides document with a Tooltip: "will linger for 10secs while you type". which means it allows you write params and waits for 10secs.
shift + tab + tab + tab + tab
It opens a small window in bottom with option(top righ corner of small window) to open full documentation in new browser tab.
in some case you can use annotation @Primary.
@Primary
class USA implements Country {}
This way it will be selected as the default autowire candididate, with no need to autowire-candidate on the other bean.
for mo deatils look at Autowiring two beans implementing same interface - how to set default bean to autowire?
DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.
That is, try adding -lpthread
to your command line.
Implementing the TimeZone class to set the timezone to the Calendar takes care of the daylight savings.
java.util.TimeZone represents a time zone offset, and also figures out daylight savings.
sample code:
TimeZone est_timeZone = TimeZoneIDProvider.getTimeZoneID(TimeZoneID.US_EASTERN).getTimeZone();
Calendar enteredCalendar = Calendar.getInstance();
enteredCalendar.setTimeZone(est_timeZone);
If on Python = 2.7:
# update different values in dictB
# I would assume only dictA should be updated,
# but the question specifies otherwise
for k in dictA.viewkeys() & dictB.viewkeys():
if dictA[k] != dictB[k]:
dictB[k]= dictA[k]
# add missing keys to dictA
dictA.update( (k,dictB[k]) for k in dictB.viewkeys() - dictA.viewkeys() )
You need to use quote marks.
font-family: "Comic Sans MS", cursive, sans-serif;
Although you really really shouldn't use comic sans. The font has massive stigma attached to it's use; it's not seen as professional at all.
I was unable to find name of an error for given code when developing in Swift. For that reason I paste minus codes for NSURLErrorDomain
taken from NSURLError.h
/*!
@enum NSURL-related Error Codes
@abstract Constants used by NSError to indicate errors in the NSURL domain
*/
NS_ENUM(NSInteger)
{
NSURLErrorUnknown = -1,
NSURLErrorCancelled = -999,
NSURLErrorBadURL = -1000,
NSURLErrorTimedOut = -1001,
NSURLErrorUnsupportedURL = -1002,
NSURLErrorCannotFindHost = -1003,
NSURLErrorCannotConnectToHost = -1004,
NSURLErrorNetworkConnectionLost = -1005,
NSURLErrorDNSLookupFailed = -1006,
NSURLErrorHTTPTooManyRedirects = -1007,
NSURLErrorResourceUnavailable = -1008,
NSURLErrorNotConnectedToInternet = -1009,
NSURLErrorRedirectToNonExistentLocation = -1010,
NSURLErrorBadServerResponse = -1011,
NSURLErrorUserCancelledAuthentication = -1012,
NSURLErrorUserAuthenticationRequired = -1013,
NSURLErrorZeroByteResource = -1014,
NSURLErrorCannotDecodeRawData = -1015,
NSURLErrorCannotDecodeContentData = -1016,
NSURLErrorCannotParseResponse = -1017,
NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
NSURLErrorFileDoesNotExist = -1100,
NSURLErrorFileIsDirectory = -1101,
NSURLErrorNoPermissionsToReadFile = -1102,
NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) = -1103,
// SSL errors
NSURLErrorSecureConnectionFailed = -1200,
NSURLErrorServerCertificateHasBadDate = -1201,
NSURLErrorServerCertificateUntrusted = -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid = -1204,
NSURLErrorClientCertificateRejected = -1205,
NSURLErrorClientCertificateRequired = -1206,
NSURLErrorCannotLoadFromNetwork = -2000,
// Download and file I/O errors
NSURLErrorCannotCreateFile = -3000,
NSURLErrorCannotOpenFile = -3001,
NSURLErrorCannotCloseFile = -3002,
NSURLErrorCannotWriteToFile = -3003,
NSURLErrorCannotRemoveFile = -3004,
NSURLErrorCannotMoveFile = -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete =-3007,
NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) = -1018,
NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) = -1019,
NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) = -1020,
NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) = -1021,
NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,
};
AndroidX is the open-source project that the Android team uses to develop, test, package, version and release libraries within Jetpack.
After hours of struggling, I solved it by including the following within app/build.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
Put these flags in your gradle.properties
android.enableJetifier=true
android.useAndroidX=true
Changes in gradle:
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0-alpha04'
When migrating on Android studio, the app/gradle file is automatically updated with the correction library impleemntations from the standard library
Refer to: https://developer.android.com/jetpack/androidx/migrate
if($('.modal').hasClass('in')) {
alert($('.modal .in').attr('id')); //ID of the opened modal
} else {
alert("No pop-up opened");
}
Using ints.sum()
has two problems:
customerssalary
, not ints
Sum()
, not sum()
.Additionally, you'll need a using directive of
using System.Linq;
Once you've got the sum, you can just divide by the length of the array to get the average - you don't need to use Average()
which will iterate over the array again.
int sum = customerssalary.Sum();
int average = sum / customerssalary.Length;
or as a double
:
double average = ((double) sum) / customerssalary.Length;
@BrenBarn's answer says it all, but if you're like me it might take a while to understand. Here's my case and how @BrenBarn's answer applies to it, perhaps it will help you.
The case
package/
__init__.py
subpackage1/
__init__.py
moduleX.py
moduleA.py
Using our familiar example, and add to it that moduleX.py has a relative import to ..moduleA. Given that I tried writing a test script in the subpackage1 directory that imported moduleX, but then got the dreaded error described by the OP.
Solution
Move test script to the same level as package and import package.subpackage1.moduleX
Explanation
As explained, relative imports are made relative to the current name. When my test script imports moduleX from the same directory, then module name inside moduleX is moduleX. When it encounters a relative import the interpreter can't back up the package hierarchy because it's already at the top
When I import moduleX from above, then name inside moduleX is package.subpackage1.moduleX and the relative import can be found
in some cases it's the best practice in other it's not a good idea it's context driven if you chose to do so using the following is the best way to pass from an activity to her sons :
Intent i = new Intent(myCurrentActivityName.this,activityIWishToRun.class);
startActivityForResult(i, GlobalDataStore.STATIC_INTEGER_VALUE);
the thing is whenever you finish() from activityIWishToRun you return to your a living activity
On the 1st iteration of the outer loop (i = 1), the inner loop will iterate 1 times
On the 2nd iteration of the outer loop (i = 2), the inner loop will iterate 2 time
On the 3rd iteration of the outer loop (i = 3), the inner loop will iterate 3 times
.
.
On the FINAL iteration of the outer loop (i = n), the inner loop will
iterate n times
So, the total number of times the statements in the inner loop will be executed will be equal to the sum of the integers from 1 to n, which is:
((n)*n) / 2 = (n^2)/2 = O(n^2) times
You have a typo - it is trustStore
.
Apart from setting the variables with System.setProperty(..)
, you can also use
-Djavax.net.ssl.keyStore=path/to/keystore.jks
If you're a C# / Java / C++ / Ruby / Python / Pick-A-Language-From-This-Century developer and you want to call your function with commas, because that's what you've always done, then you need something like this:
$myModule = New-Module -ascustomobject {
function test($arg1, $arg2) {
echo "arg1 = $arg1, and arg2 = $arg2"
}
}
Now call:
$myModule.test("ABC", "DEF")
and you'll see
arg1 = ABC, and arg2 = DEF
"the origin is at the top-left of the screen and the Y-Coordinate increases going down, while the X-Coordinate increases to the right like normal. I guess my question becomes, do I have to convert the screen coordinates to Cartesian coordinates before applying the above formula?"
If you were calculating the angle using Cartesian coordinates, and both points were in quadrant 1 (where x>0 and y>0), the situation would be identical to screen pixel coordinates (except for the upside-down-Y thing. If you negate Y to get it right-side up, it becomes quadrant 4...). Converting screen pixel coordinates to Cartesian doesnt really change the angle.
You need to put the format arguments into a tuple (add parentheses):
instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)
What you currently have is equivalent to the following:
intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl
Example:
>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'
exec sp_addlinkedserver
@server = 'local',
@srvproduct = '',
@provider='SQLNCLI',
@datasrc = @@SERVERNAME
go
create view ViewTest
as
select * from openquery(local, 'sp_who')
go
select * from ViewTest
go
Two ways
window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')
OR
window.frames['myIFrame'].contentWindow.document.getElementById('myIFrameElemId')
Yes, there is a difference. continue
forces the loop to start at the next iteration while pass
means "there is no code to execute here" and will continue through the remainder or the loop body.
Run these and see the difference:
for element in some_list:
if not element:
pass
print 1 # will print after pass
for element in some_list:
if not element:
continue
print 1 # will not print after continue
<div style="height: 100px;"> </div>
OR
<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px; }
The accepted answer seems not adequate in several situations.
To check whether the localStorage
or sessionStorage
are supported, I use the following snippet from MDN.
function storageAvailable(type) {
var storage;
try {
storage = window[type];
var x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
(storage && storage.length !== 0);
}
}
Use this snippet like this, and fallback to, for example, using cookie:
if (storageAvailable('localStorage')) {
// Yippee! We can use localStorage awesomeness
}
else {
// Too bad, no localStorage for us
document.cookie = key + "=" + encodeURIComponent(value) + expires + "; path=/";
}
I have made the fallbackstorage package which uses this snippet to check for the storage availability and fallback to a manually implemented MemoryStorage.
import {getSafeStorage} from 'fallbackstorage'
getSafeStorage().setItem('test', '1') // always work
In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.
When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).
Remember to call wait() on the child process to prevent any lingering zombies.
I can't see pass-by-reference in the examples where people try to demonstrate such. I only see pass-by-value.
In the case of variables that hold a reference to an object, the reference is the value of those variables, and therefore the reference is passed, which is then pass-by-value.
In a statement like this,
var a = {
b: "foo",
c: "bar"
};
the value of the 'a' is not the Object, but the (so far only) reference to it. In other words, the object is not in the variable a
- a reference to it is. I think this is something that seems difficult for programmers who are mainly only familiar with JavaScript. But it is easy for people who know also e.g. Java, C#, and C.
After a long struggle, I've switched my node architecture to x86 and it worked like a charm.
You can add multiple classes by separating classes names by spaces
$('.page-address-edit').addClass('test1 test2 test3');
Here is a better way to loop over files as it handles spaces and newlines in file names:
#!/bin/bash
find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
echo "$line"
ls -l "$line"
done
You're referencing a DOM element when doing something like $('#lastName')
. That's an element with id
attribute "lastName". Why do that? You want to reference the value stored in a local variable, completely unrelated. Try this (assuming the assignment to formObject
is in the same scope as the variable declarations) -
var formObject = {
formObject: [
{
firstName:firstName, // no need to quote variable names
lastName:lastName
},
{
phoneNumber:phoneNumber,
address:address
}
]
};
This seems very odd though: you're creating an object "formObject" that contains a member called "formObject" that contains an array of objects.
this is what you need, the child combinator:
select>option:hover
{
color: #1B517E;
cursor: pointer;
}
Try it, works perfect.
Here's the reference: http://www.w3schools.com/css/css_combinators.asp
I was running some of the answers to see what is the fastest way for a large number. So, I found that we can convert the int to an array and it can give the correct results and it is faster.
arrayint=np.array(myInt)
newList = myList / arrayint
This a comparison of all answers above
import numpy as np
import time
import random
myList = random.sample(range(1, 100000), 10000)
myInt = 10
start_time = time.time()
arrayint=np.array(myInt)
newList = myList / arrayint
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = np.array(myList) / myInt
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = [x / myInt for x in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
myList[:] = [x / myInt for x in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = map(lambda x: x/myInt, myList)
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = [i/myInt for i in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = np.divide(myList, myInt)
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = np.divide(myList, myInt)
end_time = time.time()
print(newList,end_time-start_time)
It means the CPU attempted to execute an instruction it didn't understand. This could be caused by corruption I guess, or maybe it's been compiled for the wrong architecture (in which case I would have thought the O/S would refuse to run the executable). Not entirely sure what the root issue is.
https://www.kaggle.com/jboysen/quick-gz-pandas-tutorial
Please follow this link.
import pandas as pd
traffic_station_df = pd.read_csv('C:\\Folders\\Jupiter_Feed.txt.gz', compression='gzip',
header=1, sep='\t', quotechar='"')
#traffic_station_df['Address'] = 'address'
#traffic_station_df.append(traffic_station_df)
print(traffic_station_df)
I have create an extension method based on position of items in a list which is bind with recycler view
Smooth scroll in large list takes longer time to scroll , use this to improve speed of scrolling and also have the smooth scroll animation. Cheers!!
fun RecyclerView?.perfectScroll(size: Int,up:Boolean = true ,smooth: Boolean = true) {
this?.apply {
if (size > 0) {
if (smooth) {
val minDirectScroll = 10 // left item to scroll
//smooth scroll
if (size > minDirectScroll) {
//scroll directly to certain position
val newSize = if (up) minDirectScroll else size - minDirectScroll
//scroll to new position
val newPos = newSize - 1
//direct scroll
scrollToPosition(newPos)
//smooth scroll to rest
perfectScroll(minDirectScroll, true)
} else {
//direct smooth scroll
smoothScrollToPosition(if (up) 0 else size-1)
}
} else {
//direct scroll
scrollToPosition(if (up) 0 else size-1)
}
}
} }
Just call the method anywhere using
rvList.perfectScroll(list.size,up=true,smooth=true)
#since this was yesterday
date -dyesterday +%Y%m%d
#more precise, and more recommended
date -d'27 JUN 2011' +%Y%m%d
#assuming this is similar to yesterdays `date` question from you
#http://stackoverflow.com/q/6497525/638649
date -d'last-monday' +%Y%m%d
#going on @seth's comment you could do this
DATE="27 jun 2011"; date -d"$DATE" +%Y%m%d
#or a method to read it from stdin
read -p " Get date >> " DATE; printf " AS YYYYMMDD format >> %s" `date
-d"$DATE" +%Y%m%d`
#which then outputs the following:
#Get date >> 27 june 2011
#AS YYYYMMDD format >> 20110627
#if you really want to use awk
echo "27 june 2011" | awk '{print "date -d\""$1FS$2FS$3"\" +%Y%m%d"}' | bash
#note | bash just redirects awk's output to the shell to be executed
#FS is field separator, in this case you can use $0 to print the line
#But this is useful if you have more than one date on a line
note this only works on GNU date
I have read that:
Solaris version of date, which is unable to support
-d
can be resolve with replacing sunfreeware.com version of date
Cmd.exe
)When the Docker CLI is used from the Windows Cmd.exe
, use %cd%
to mount the current directory:
echo test > test.txt
docker run --rm -v %cd%:/data busybox ls -ls /data/test.txt
When the Docker CLI is used from the Git Bash (MinGW), mounting the current directory may fail due to a POSIX path conversion: Docker mounted volume adds ;C to end of windows path when translating from linux style path.
/
To skip the path conversion, POSIX paths have to be prefixed with the slash (/
) to have leading double slash (//
), including /$(pwd)
touch test.txt
docker run --rm -v /$(pwd):/data busybox ls -la //data/test.txt
Disable the POSIX path conversion in Git Bash (MinGW) by setting MSYS_NO_PATHCONV=1
environment variable at the command level
touch test.txt
MSYS_NO_PATHCONV=1 docker run --rm -v $(pwd):/data busybox ls -la /data/test.txt
or shell (system) level
export MSYS_NO_PATHCONV=1
touch test.txt
docker run --rm -v $(pwd):/data busybox ls -la /data/test.txt
This seems to do the job for me:
[\S]{2,} [\S]{2,}( [\S]{2,})*
I got rid of this same error in index.ts
with these combined properties:
In tsconfig.json:
"compilerOptions": {
"target": "ES6"
And in package.json:
"main": "index.ts",
"scripts": {
"start": "tsc -p tsconfig.json && node index.js"
The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)
To link with gdi32:
This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a
has no advantage over gdi32
other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib
for MSVC).
For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).
Here is my approach, clunky as it is and available in github:
Put in the very first notebook cell, the import cell:
from IPythonTOC import IPythonTOC
toc = IPythonTOC()
Somewhere after the import cell, put in the genTOCEntry cell but don't run it yet:
''' if you called toc.genTOCMarkdownCell before running this cell,
the title has been set in the class '''
print toc.genTOCEntry()
Below the genTOCEntry cell`, make a TOC cell as a markdown cell:
<a id='TOC'></a>
#TOC
As the notebook is developed, put this genTOCMarkdownCell before starting a new section:
with open('TOCMarkdownCell.txt', 'w') as outfile:
outfile.write(toc.genTOCMarkdownCell('Introduction'))
!cat TOCMarkdownCell.txt
!rm TOCMarkdownCell.txt
Move the genTOCMarkdownCell down to the point in your notebook where you want to start a new section and make the argument to genTOCMarkdownCell the string title for your new section then run it. Add a markdown cell right after it and copy the output from genTOCMarkdownCell into the markdown cell that starts your new section. Then go to the genTOCEntry cell near the top of your notebook and run it. For example, if you make the argument to genTOCMarkdownCell as shown above and run it, you get this output to paste into the first markdown cell of your newly indexed section:
<a id='Introduction'></a>
###Introduction
Then when you go to the top of your notebook and run genTocEntry, you get the output:
[Introduction](#Introduction)
Copy this link string and paste it into the TOC markdown cell as follows:
<a id='TOC'></a>
#TOC
[Introduction](#Introduction)
After you edit the TOC cell to insert the link string and then you press shift-enter, the link to your new section will appear in your notebook Table of Contents as a web link and clicking it will position the browser to your new section.
One thing I often forget is that clicking a line in the TOC makes the browser jump to that cell but doesn't select it. Whatever cell was active when we clicked on the TOC link is still active, so a down or up arrow or shift-enter refers to still active cell, not the cell we got by clicking on the TOC link.
I use this handy function:
By downloading it with a 4094 byte step it will not full your memory
function download($file_source, $file_target) {
$rh = fopen($file_source, 'rb');
$wh = fopen($file_target, 'w+b');
if (!$rh || !$wh) {
return false;
}
while (!feof($rh)) {
if (fwrite($wh, fread($rh, 4096)) === FALSE) {
return false;
}
echo ' ';
flush();
}
fclose($rh);
fclose($wh);
return true;
}
Usage:
$result = download('http://url','path/local/file');
You can then check if everything is ok with:
if (!$result)
throw new Exception('Download error...');
div.section > div
Actually
{
@synchronized(self) {
return [[myString retain] autorelease];
}
}
transforms directly into:
// needs #import <objc/objc-sync.h>
{
objc_sync_enter(self)
id retVal = [[myString retain] autorelease];
objc_sync_exit(self);
return retVal;
}
This API available since iOS 2.0 and imported using...
#import <objc/objc-sync.h>
You can define the behavior globally:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
So you don't have to redefine it every time:
$http.post("/handle/post", {
foo: "FOO",
bar: "BAR"
}).success(function (data, status, headers, config) {
// TODO
}).error(function (data, status, headers, config) {
// TODO
});
package SortedSet;
import java.util.*;
public class HashMapValueSort {
public static void main(String[] args){
final Map<Integer, String> map = new HashMap<Integer,String>();
map.put(4,"Mango");
map.put(3,"Apple");
map.put(5,"Orange");
map.put(8,"Fruits");
map.put(23,"Vegetables");
map.put(1,"Zebra");
map.put(5,"Yellow");
System.out.println(map);
final HashMapValueSort sort = new HashMapValueSort();
final Set<Map.Entry<Integer, String>> entry = map.entrySet();
final Comparator<Map.Entry<Integer, String>> comparator = new Comparator<Map.Entry<Integer, String>>() {
@Override
public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
String value1 = o1.getValue();
String value2 = o2.getValue();
return value1.compareTo(value2);
}
};
final SortedSet<Map.Entry<Integer, String>> sortedSet = new TreeSet(comparator);
sortedSet.addAll(entry);
final Map<Integer,String> sortedMap = new LinkedHashMap<Integer, String>();
for(Map.Entry<Integer, String> entry1 : sortedSet ){
sortedMap.put(entry1.getKey(),entry1.getValue());
}
System.out.println(sortedMap);
}
}
If we are talking about FLYME OS (Meizu) ONLY there are it's own Security app with permissions.
To open it use following intent:
public static void openFlymeSecurityApp(Activity context) {
Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
try {
context.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Of-cause BuildConfig is your app's BuildConfig.
All answers above contribute important info on the original question. However, there is a generalization that seems wrong.
It is possible to set width and height to at least one inline element (that I can think of) – the <img>
element.
Both accepted answers here and on this duplicate state that this is not possible but this doesn’t seem like a valid general rule.
Example:
img {_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
border: 1px solid red;_x000D_
}
_x000D_
<img src="#" />
_x000D_
The img
has display: inline
, but its width
and height
were successfully set.
can also appear if:
struct foo { int x, int y, int z }foo;
foo.x=12
instead of
struct foo { int x; int y; int z; }foo;
foo.x=12
There is a difference between what JSON.parse() and eval() will accept. Try eval on this:
var x = "{\"shoppingCartName\":\"shopping_cart:2000\"}"
eval(x) //won't work
JSON.parse(x) //does work
See this example.
SQL Server returns messages after a batch of statements has been executed. Normally, you'd use SQL GO
to indicate the end of a batch and to retrieve the results:
PRINT '1'
GO
WAITFOR DELAY '00:00:05'
PRINT '2'
GO
WAITFOR DELAY '00:00:05'
PRINT '3'
GO
In this case, however, the print statement you want returned immediately is in the middle of a loop, so the print statements cannot be in their own batch. The only command I know of that will return in the middle of a batch is RAISERROR (...) WITH NOWAIT
, which gbn has provided as an answer as I type this.
As an extension to what have been proposed by Nico Coallier (apply to multiple columns) and U10-Forward(using apply style of methods), and summarising it into a one-liner I propose:
df.loc[:,['col1','col2']].transform(lambda x: x.map(lambda x: {1: "A", 2: "B"}.get(x,x))
The .transform()
processes each column as a series. Contrary to .apply()
which passes the columns aggregated in a DataFrame.
Consequently you can apply the Series method map()
.
Finally, and I discovered this behaviour thanks to U10, you can use the whole Series in the .get() expression. Unless I have misunderstood its behaviour and it processes sequentially the series instead of bitwisely.
The .get(x,x)
accounts for the values you did not mention in your mapping dictionary which would be considered as Nan otherwise by the .map()
method
Here's a link to marketplace for extension. Extension "compareit" helps to compare two files wich you can choose from your current project and other directory on your computer or clipboard.
Use text-align: center;
on the block container of the icon (the <td>
) - text-align doesn't apply to inline elements, only block containers:
td {
text-align: center;
}
To connect from Terminal to AWS AMI:
chmod 400 mykey.pem
ssh -i mykey.pem [email protected]
If you could do this, it will represent a big security problem, as you can access your filesystem, and potentially act on the data available there... Luckily it's not possible to do what you're trying to do.
If you need local resources to be accessed, you can try to start a web server on your machine, and in this case your method will work. Other workarounds are possible, such as acting on Chrome settings, but I always prefer the clean way, installing a local web server, maybe on a different port (no, it's not so difficult!).
See also:
I was just giving a try for max lines on windows 7 i can set using mode con
command and found it to be 32766 2^15-2 and you can set it with following command
mode con lines=32766
although you can set screen buffer size from the GUI too, but the max you can get is 9999.
Recursively create .gitkeep files
find . -type d -empty -not -path "./.git/*" -exec touch {}/.gitkeep \;
Note that the approach from @AndrewMyers's answer matches the entire string to the regular expression, with the effect of anchoring the regular expression at both ends of the string using ^
and $
. Example:
scala> val MY_RE = "(foo|bar).*".r
MY_RE: scala.util.matching.Regex = (foo|bar).*
scala> val result = "foo123" match { case MY_RE(m) => m; case _ => "No match" }
result: String = foo
scala> val result = "baz123" match { case MY_RE(m) => m; case _ => "No match" }
result: String = No match
scala> val result = "abcfoo123" match { case MY_RE(m) => m; case _ => "No match" }
result: String = No match
And with no .*
at the end:
scala> val MY_RE2 = "(foo|bar)".r
MY_RE2: scala.util.matching.Regex = (foo|bar)
scala> val result = "foo123" match { case MY_RE2(m) => m; case _ => "No match" }
result: String = No match
The following code worked for me,
function timeDiffCalc(dateNow,dateFuture) {
var newYear1 = new Date(dateNow);
var newYear2 = new Date(dateFuture);
var dif = (newYear2 - newYear1);
var dif = Math.round((dif/1000)/60);
console.log(dif);
}
You can solve your problem most concisely with a predicate written using anonymous method syntax:
MyClass found = list.Find(item => item.GetID() == ID);
If you already have the package name you wish to activate, you can use the following code which is a bit more generic:
PackageManager pm = context.getPackageManager();
Intent appStartIntent = pm.getLaunchIntentForPackage(appPackageName);
if (null != appStartIntent)
{
context.startActivity(appStartIntent);
}
I found that it works better for cases where the main activity was not found by the regular method of start the MAIN activity.
I've seen various versions of making a case class mimic an enumeration. Here is my version:
trait CaseEnumValue {
def name:String
}
trait CaseEnum {
type V <: CaseEnumValue
def values:List[V]
def unapply(name:String):Option[String] = {
if (values.exists(_.name == name)) Some(name) else None
}
def unapply(value:V):String = {
return value.name
}
def apply(name:String):Option[V] = {
values.find(_.name == name)
}
}
Which allows you to construct case classes that look like the following:
abstract class Currency(override name:String) extends CaseEnumValue {
}
object Currency extends CaseEnum {
type V = Site
case object EUR extends Currency("EUR")
case object GBP extends Currency("GBP")
var values = List(EUR, GBP)
}
Maybe someone could come up with a better trick than simply adding a each case class to the list like I did. This was all I could come up with at the time.
You can use json module of python to pretty print.
>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
"4": 5,
"6": 7
}
So, in your case
>>> print json.dumps(json_output, indent=4)
Had similar problem. Added in build.gradle and it worked for me.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Try to modify the eclipse.ini
so that both Xms
and Xmx
are of the same value:
-Xms6000m
-Xmx6000m
This should force the Eclipse's VM to allocate 6GB
of heap right from the beginning.
But be careful about either using the eclipse.ini
or the command-line ./eclipse/eclipse -vmargs ...
. It should work in both cases but pick one and try to stick with it.
This uses rand with a seed like one of the other answers, but it is not necessary to provide a seed on every call. Providing it on the first call is sufficient.
This is my modified code.
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND object_id = OBJECT_ID(N'usp_generateIdentifier'))
DROP PROCEDURE usp_generateIdentifier
GO
create procedure usp_generateIdentifier
@minLen int = 1
, @maxLen int = 256
, @seed int output
, @string varchar(8000) output
as
begin
set nocount on;
declare @length int;
declare @alpha varchar(8000)
, @digit varchar(8000)
, @specials varchar(8000)
, @first varchar(8000)
select @alpha = 'qwertyuiopasdfghjklzxcvbnm'
, @digit = '1234567890'
, @specials = '_@#$&'
select @first = @alpha + '_@';
-- Establish our rand seed and store a new seed for next time
set @seed = (rand(@seed)*2147483647);
select @length = @minLen + rand() * (@maxLen-@minLen);
--print @length
declare @dice int;
select @dice = rand() * len(@first);
select @string = substring(@first, @dice, 1);
while 0 < @length
begin
select @dice = rand() * 100;
if (@dice < 10) -- 10% special chars
begin
select @dice = rand() * len(@specials)+1;
select @string = @string + substring(@specials, @dice, 1);
end
else if (@dice < 10+10) -- 10% digits
begin
select @dice = rand() * len(@digit)+1;
select @string = @string + substring(@digit, @dice, 1);
end
else -- rest 80% alpha
begin
select @dice = rand() * len(@alpha)+1;
select @string = @string + substring(@alpha, @dice, 1);
end
select @length = @length - 1;
end
end
go
If you're open to out-of-the-DB solution: You could set up a cron job that runs a script that will itself call the procedure.
I'm a complete noob on Entity but this is how I would do it in theory...
var name = yourDbContext.MyTable.Find(1).Name;
If It's A Primary Key.
-- OR --
var name = yourDbContext.MyTable.SingleOrDefault(mytable => mytable.UserId == 1).Name;
-- OR --
For whole Column:
var names = yourDbContext.MyTable
.Where(mytable => mytable.UserId == 1)
.Select(column => column.Name); //You can '.ToList();' this....
But "oh Geez Rick, What do I know..."
It's the python path problem.
In my case, I have python installed in:
/Library/Frameworks/Python.framework/Versions/2.6/bin/python,
and there is no site-packages directory within the python2.6.
The package(SOAPpy) I installed by pip is located
/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/
And site-package is not in the python path, all I did is add site-packages to PYTHONPATH permanently.
In the text file that pops up, add this line at the end:
export PYTHONPATH=$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/
I'll try to give a proper answer myself:
The only punctuations that should be allowed in a name are full stop, apostrophe and hyphen. I haven't seen any other case in the list of corner cases.
Regarding numbers, there's only one case with an 8. I think I can safely disallow that.
Regarding letters, any letter is valid.
I also want to include space.
This would sum up to this regex:
^[\p{L} \.'\-]+$
This presents one problem, i.e. the apostrophe can be used as an attack vector. It should be encoded.
So the validation code should be something like this (untested):
var name = nameParam.Trim();
if (!Regex.IsMatch(name, "^[\p{L} \.\-]+$"))
throw new ArgumentException("nameParam");
name = name.Replace("'", "'"); //' does not work in IE
Can anyone think of a reason why a name should not pass this test or a XSS or SQL Injection that could pass?
complete tested solution
using System;
using System.Text.RegularExpressions;
namespace test
{
class MainClass
{
public static void Main(string[] args)
{
var names = new string[]{"Hello World",
"John",
"João",
"???",
"???",
"??",
"??",
"??????",
"Te???e?a",
"?????????",
"???? ?????",
"?????????",
"??????",
"?",
"D'Addario",
"John-Doe",
"P.A.M.",
"' --",
"<xss>",
"\""
};
foreach (var nameParam in names)
{
Console.Write(nameParam+" ");
var name = nameParam.Trim();
if (!Regex.IsMatch(name, @"^[\p{L}\p{M}' \.\-]+$"))
{
Console.WriteLine("fail");
continue;
}
name = name.Replace("'", "'");
Console.WriteLine(name);
}
}
}
}
For me, the below helped
Find org.apache.http.legacy.jar
which is in Android/Sdk/platforms/android-23/optional,
add it to your dependency.
My Python 3 version
base_list = list("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
base = len(base_list)
def encode(num: int):
result = []
if num == 0:
result.append(base_list[0])
while num > 0:
result.append(base_list[num % base])
num //= base
print("".join(reversed(result)))
def decode(code: str):
num = 0
code_list = list(code)
for index, code in enumerate(reversed(code_list)):
num += base_list.index(code) * base ** index
print(num)
if __name__ == '__main__':
encode(341413134141)
decode("60FoItT")
It points to the docker host! I followed these steps:
$ boot2docker start
Waiting for VM and Docker daemon to start...
..............................
Started.
To connect the Docker client to the Docker daemon, please set:
export DOCKER_HOST=tcp://192.168.59.103:2375
$ export DOCKER_HOST=tcp://192.168.59.103:2375
$ docker run ubuntu:14.04 /bin/echo 'Hello world'
Unable to find image 'ubuntu:14.04' locally
Pulling repository ubuntu
9cbaf023786c: Download complete
511136ea3c5a: Download complete
97fd97495e49: Download complete
2dcbbf65536c: Download complete
6a459d727ebb: Download complete
8f321fc43180: Download complete
03db2b23cf03: Download complete
Hello world
1)What is the difference between both the way of creating class objects.
First one is a pointer to a constructed object in heap (by new
).
Second one is an object that implicitly constructed. (Default constructor)
2)If i am creating object like Example example; how to use that in an singleton class.
It depends on your goals, easiest is put it as a member in class simply.
A sample of a singleton class which has an object from Example
class:
class Sample
{
Example example;
public:
static inline Sample *getInstance()
{
if (!uniqeInstance)
{
uniqeInstance = new Sample;
}
return uniqeInstance;
}
private:
Sample();
virtual ~Sample();
Sample(const Sample&);
Sample &operator=(const Sample &);
static Sample *uniqeInstance;
};
Assuming that your table name is city
and your existing Primary Key is pk_city
, you should be able to do the following:
ALTER TABLE city
DROP CONSTRAINT pk_city;
ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);
Make sure that there are no records where time
is NULL
, otherwise you won't be able to re-create the constraint.
Simple javascript document navigation to "#" will do it.
window.onload = function()
{
document.location.href = "#";
}
This will force the navigation bar to remove itself on load.
I had a similar exception (but different problem) - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.bson.Document
, and fortunately it's solved easier:
Instead of
List<Document> docs = obj.get("documents");
Document doc = docs.get(0)
which gives error on second line, One can use
List<Document> docs = obj.get("documents");
Document doc = new Document(docs.get(0));
Calculate the last date of the month is quite simple calculation -
1 - Find the total months count till today's date using DATEDIFF function -
Select DATEDIFF(MM,0,GETDATE())
Output - 1374, If getdate() output is "2014-07-23 19:33:46.850"
2 -Increment by 1 into total months count -
Select DATEDIFF(MM,0,GETDATE())+1
Output - 1375, If getdate() output is "2014-07-23 19:33:46.850"
3 - Get the first date of next month -
Select DATEADD(MM,DATEDIFF(MM,0,GETDATE())+1,0)
Output - '2014-08-01 00:00:00.000', If getdate() output is "2014-07-23 19:33:46.850"
4 - Subtract by -1 into the first date of next month, which will return last date of the current month -
Select DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,0,GETDATE())+1,0))
Output - '2014-07-31 00:00:00.000', If getdate() output is "2014-07-23 19:33:46.850"
In the same manner of calculation we can achieve the -
This error means you can not directly load data from file system because there are security issues behind this. The only solution that I know is create a web service to serve load files.
Tools --> Preferences
, as shown in below image.expand Database --> select Advanced --> under "Tnsnames Directory" --> Browse the directory
where tnsnames.ora present.Drive:\oracle\product\10x.x.x\client_x\NETWORK\ADMIN
Now you can connect via the TNSnames options.
Swift:
I have a UILabel which shows TimeStamp over a Camera Preview.
var timeStampTimer : NSTimer?
var dateEnabled: Bool?
var timeEnabled: Bool?
@IBOutlet weak var timeStampLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//Setting Initial Values to be false.
dateEnabled = false
timeEnabled = false
}
override func viewWillAppear(animated: Bool) {
//Current Date and Time on Preview View
timeStampLabel.text = timeStamp
self.timeStampTimer = NSTimer.scheduledTimerWithTimeInterval(1.0,target: self, selector: Selector("updateCurrentDateAndTimeOnTimeStamperLabel"),userInfo: nil,repeats: true)
}
func updateCurrentDateAndTimeOnTimeStamperLabel()
{
//Every Second, it updates time.
switch (dateEnabled, timeEnabled) {
case (true?, true?):
timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .LongStyle, timeStyle: .MediumStyle)
break;
case (true?, false?):
timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .LongStyle, timeStyle: .NoStyle)
break;
case (false?, true?):
timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .MediumStyle)
break;
case (false?, false?):
timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .NoStyle)
break;
default:
break;
}
}
I am setting up a setting Button to trigger a alertView.
@IBAction func settingsButton(sender : AnyObject) {
let cameraSettingsAlert = UIAlertController(title: NSLocalizedString("Please choose a course", comment: ""), message: NSLocalizedString("", comment: ""), preferredStyle: .ActionSheet)
let timeStampOnAction = UIAlertAction(title: NSLocalizedString("Time Stamp on Photo", comment: ""), style: .Default) { action in
self.dateEnabled = true
self.timeEnabled = true
}
let timeStampOffAction = UIAlertAction(title: NSLocalizedString("TimeStamp Off", comment: ""), style: .Default) { action in
self.dateEnabled = false
self.timeEnabled = false
}
let dateOnlyAction = UIAlertAction(title: NSLocalizedString("Date Only", comment: ""), style: .Default) { action in
self.dateEnabled = true
self.timeEnabled = false
}
let timeOnlyAction = UIAlertAction(title: NSLocalizedString("Time Only", comment: ""), style: .Default) { action in
self.dateEnabled = false
self.timeEnabled = true
}
let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel) { action in
}
cameraSettingsAlert.addAction(cancel)
cameraSettingsAlert.addAction(timeStampOnAction)
cameraSettingsAlert.addAction(timeStampOffAction)
cameraSettingsAlert.addAction(dateOnlyAction)
cameraSettingsAlert.addAction(timeOnlyAction)
self.presentViewController(cameraSettingsAlert, animated: true, completion: nil)
}
.border-blue.background { ... }
is for one item with multiple classes.
.border-blue, .background { ... }
is for multiple items each with their own class.
.border-blue .background { ... }
is for one item where '.background' is the child of '.border-blue'.
See Chris' answer for a more thorough explanation.
If you want to simply access a global variable you just use its name. However to change its value you need to use the global
keyword.
E.g.
global someVar
someVar = 55
This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.
The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.
The other response shows this, but essentially you just need to create a SqlParameter
, set the Direction
to Output
, and add it to the SqlCommand
's Parameters
collection. Then execute the stored procedure and get the value of the parameter.
Using your code sample:
// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("sproc", conn))
{
// Create parameter with Direction as Output (and correct name and type)
SqlParameter outputIdParam = new SqlParameter("@ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(outputIdParam);
conn.Open();
cmd.ExecuteNonQuery();
// Some various ways to grab the output depending on how you would like to
// handle a null value returned from the query (shown in comment for each).
// Note: You can use either the SqlParameter variable declared
// above or access it through the Parameters collection by name:
// outputIdParam.Value == cmd.Parameters["@ID"].Value
// Throws FormatException
int idFromString = int.Parse(outputIdParam.Value.ToString());
// Throws InvalidCastException
int idFromCast = (int)outputIdParam.Value;
// idAsNullableInt remains null
int? idAsNullableInt = outputIdParam.Value as int?;
// idOrDefaultValue is 0 (or any other value specified to the ?? operator)
int idOrDefaultValue = outputIdParam.Value as int? ?? default(int);
conn.Close();
}
Be careful when getting the Parameters[].Value
, since the type needs to be cast from object
to what you're declaring it as. And the SqlDbType
used when you create the SqlParameter
needs to match the type in the database. If you're going to just output it to the console, you may just be using Parameters["@Param"].Value.ToString()
(either explictly or implicitly via a Console.Write()
or String.Format()
call).
EDIT: Over 3.5 years and almost 20k views and nobody had bothered to mention that it didn't even compile for the reason specified in my "be careful" comment in the original post. Nice. Fixed it based on good comments from @Walter Stabosz and @Stephen Kennedy and to match the update code edit in the question from @abatishchev.
In my case, I was getting value of <input type="text">
with JQuery and I did it like this:
var newUserInfo = { "lastName": inputLastName[0].value, "userName": inputUsername[0].value,
"firstName": inputFirstName[0] , "email": inputEmail[0].value}
And I was constantly getting this exception
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: java.io.PushbackInputStream@39cb6c98; line: 1, column: 54] (through reference chain: com.springboot.domain.User["firstName"]).
And I banged my head for like an hour until I realised that I forgot to write .value
after this"firstName": inputFirstName[0]
.
So, the correct solution was:
var newUserInfo = { "lastName": inputLastName[0].value, "userName": inputUsername[0].value,
"firstName": inputFirstName[0].value , "email": inputEmail[0].value}
I came here because I had this problem and I hope I save someone else hours of misery.
Cheers :)
I've just had this problem. after a day of checking finally I've got the answer with that The mysql.sock file is created when MariaDB starts and is removed when MariaDB is shutdown. It won't exist if MariaDB is not running. maybe you didn't install MariaDB. YOU COULD FOLLOW THE INSTRUCTION BELOW: https://www.linode.com/docs/databases/mariadb/how-to-install-mariadb-on-centos-7 BEST
Because my edits to the above were rejected (did any of you actually try?), here's what you really need to make this work:
Windows (And Mac Office 2011+):
(Excel Timestamp - 25569) * 86400
(Unix Timestamp / 86400) + 25569
MAC OS X (pre Office 2011):
(Excel Timestamp - 24107) * 86400
(Unix Timestamp / 86400) + 24107
The same error may occur after renaming packages. Check the value in string.xml for android:authorities
from AndroidManifest.xml.
<provider
android:authorities="@string/content_authority"
android:name=".data.Provider"
... />
In string.xml the value should be the same as your package name, declared in manifest.
<string name="content_authority">com.whatever.android.sunshine.app</string>
You can use this:
Collections.sort(list, org.joda.time.DateTimeComparator.getInstance());
You can use org.apache.commons.lang.time.DateUtils
to make it cleaner:
(firstDate.getTime() - secondDate.getTime()) / DateUtils.MILLIS_PER_SECOND
On Windows or Mac, you can find this setting under the General ? Editors ? Text Editors menu.
You can use some code like this, you can adjust a height and width as per your need
protected void button_Click(object sender, EventArgs e)
{
// open a pop up window at the center of the page.
ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "var Mleft = (screen.width/2)-(760/2);var Mtop = (screen.height/2)-(700/2);window.open( 'your_page.aspx', null, 'height=700,width=760,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=\'+Mtop+\', left=\'+Mleft+\'' );", true);
}
Here is my solution
Use androidx.appcompat.app.AppCompatActivity
for the activity that contains the NavHostFragment
fragment.
Define the following interface and implement it in all navigation destination fragments
interface InterceptionInterface {
fun onNavigationUp(): Boolean
fun onBackPressed(): Boolean
}
In your activity override onSupportNavigateUp
and onBackPressed
:
override fun onSupportNavigateUp(): Boolean {
return getCurrentNavDest().onNavigationUp() || navigation_host_fragment.findNavController().navigateUp()
}
override fun onBackPressed() {
if (!getCurrentNavDest().onBackPressed()){
super.onBackPressed()
}
}
private fun getCurrentNavDest(): InterceptionInterface {
val currentFragment = navigation_host_fragment.childFragmentManager.primaryNavigationFragment as InterceptionInterface
return currentFragment
}
This solution has the advantage, that the navigation destination fragments don't need to worry about the unregistering of their listeners as soon as they are detached.
It evaluates at runtime, so you can switch the type like you can in JavaScript to whatever you want. This is legit:
dynamic i = 12;
i = "text";
And so you can change the type as you need. Use it as a last resort; it i s beneficial, but I heard a lot goes on under the scenes in terms of generated IL and that can come at a performance price.
Just use ng-repeat="(sectionIndex, section) in sections"
and that will be useable on the next level ng-repeat down.
<ul ng-repeat="(sectionIndex, section) in sections">
<li class="section_title {{section.active}}" >
{{section.name}}
</li>
<ul>
<li ng-repeat="tutorial in section.tutorials">
{{tutorial.name}}, Your section index is {{sectionIndex}}
</li>
</ul>
</ul>
Here's a more terse approach that was introduced in 2012:
myInt = @(myFloat).intValue;
By doing a simple import you can access the image in React
import logo from "../images/logo.png";
<img src={logo}/>
Everything solved! Just a simple fix =)
In my case, I use below command:
git diff <branch name> -- <path + file name>
This command can help you compare same file in two different branches