For Mac OS X 10.9.3 and Vagrant 1.6.3 and VirtualBox 4.3.6 this problem was fixed with restarting the VirtualBox
sudo "/Library/Application Support/VirtualBox/LaunchDaemons/VirtualBoxStartup.sh" restart
I found something almost working here https://stackoverflow.com/questions/21819858/how-to-wrap-async-function-calls-into-a-sync-function-in-node-js-or-ja vascript
`function AnticipatedSyncFunction(){
var ret;
setTimeout(function(){
var startdate = new Date()
ret = "hello" + startdate;
},3000);
while(ret === undefined) {
require('deasync').runLoopOnce();
}
return ret;
}
var output = AnticipatedSyncFunction();
var startdate = new Date()
console.log(startdate)
console.log("output="+output);`
The unique problem is the date printed isn't correct but the process at least is sequential.
I dont see anyone mentioning the ClassInitialize
attribute method. The attributes are pretty straight forward.
Create methods that are marked with either the [ClassInitialize()]
or [TestInitialize()]
attribute to prepare aspects of the environment in which your unit test will run. The purpose of this is to establish a known state for running your unit test. For example, you may use the [ClassInitialize()]
or the [TestInitialize()]
method to copy, alter, or create certain data files that your test will use.
Create methods that are marked with either the [ClassCleanup()]
or [TestCleanUp{}]
attribute to return the environment to a known state after a test has run. This might mean the deletion of files in folders or the return of a database to a known state. An example of this is to reset an inventory database to an initial state after testing a method that is used in an order-entry application.
[ClassInitialize()]
Use ClassInitialize
to run code before you
run the first test in the class.
[ClassCleanUp()]
Use ClassCleanup
to run code after all tests in
a class have run.
[TestInitialize()]
Use TestInitialize
to run code before you run
each test.
[TestCleanUp()]
Use TestCleanup
to run code after each test has
run.
I suggest wrapping your call to requestAnimationFrame
in a setTimeout
:
const fps = 25;
function animate() {
// perform some animation task here
setTimeout(() => {
requestAnimationFrame(animate);
}, 1000 / fps);
}
animate();
You need to call requestAnimationFrame
from within setTimeout
, rather than the other way around, because requestAnimationFrame
schedules your function to run right before the next repaint, and if you delay your update further using setTimeout
you will have missed that time window. However, doing the reverse is sound, since you’re simply waiting a period of time before making the request.
Here is my solution. @Maxim Shoustin's solution has some issue with sorting. I also wrap the whole thing to a directive. The only dependency is UI.Bootstrap.pagination, which did a great job on pagination.
Here is the plunker
Here is the github source code.
Edit: please see my other answer, as you probably don't need this now.
As you said, in API levels 11+ a HTML5VideoFullScreen$VideoSurfaceView is passed. But I don't think you are right when you say that "it doens't have a MediaPlayer".
This is the way to reach the MediaPlayer instance from the HTML5VideoFullScreen$VideoSurfaceView instance using reflection:
@SuppressWarnings("rawtypes")
Class c1 = Class.forName("android.webkit.HTML5VideoFullScreen$VideoSurfaceView");
Field f1 = c1.getDeclaredField("this$0");
f1.setAccessible(true);
@SuppressWarnings("rawtypes")
Class c2 = f1.getType().getSuperclass();
Field f2 = c2.getDeclaredField("mPlayer");
f2.setAccessible(true);
Object ___html5VideoViewInstance = f1.get(focusedChild); // Look at the code in my other answer to this same question to see whats focusedChild
Object ___mpInstance = f2.get(___html5VideoViewInstance); // This is the MediaPlayer instance.
So, now you could set the onCompletion listener of the MediaPlayer instance like this:
OnCompletionListener ocl = new OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
// Do stuff
}
};
Method m1 = f2.getType().getMethod("setOnCompletionListener", new Class[] { Class.forName("android.media.MediaPlayer$OnCompletionListener") });
m1.invoke(___mpInstance, ocl);
The code doesn't fail but I'm not completely sure if that onCompletion listener will really be called or if it could be useful to your situation. But just in case someone would like to try it.
You can use guide=FALSE
in scale_..._...()
to suppress legend.
For your example you should use scale_colour_continuous()
because length
is continuous variable (not discrete).
(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
scale_colour_continuous(guide = FALSE) +
geom_point()
)
Or using function guides()
you should set FALSE
for that element/aesthetic that you don't want to appear as legend, for example, fill
, shape
, colour
.
p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
geom_point()
p0+guides(colour=FALSE)
Both provided solutions work in new ggplot2
version 2.0.0 but movies
dataset is no longer present in this library. Instead you have to use new package ggplot2movies
to check those solutions.
library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")
For people that find this question by searching for the error message, you can also see this error if you make a mistake in your @JsonProperty
annotations such that you annotate a List
-typed property with the name of a single-valued field:
@JsonProperty("someSingleValuedField") // Oops, should have been "someMultiValuedField"
public List<String> getMyField() { // deserialization fails - single value into List
return myField;
}
If you do not need the recording and playback functionality in your app, using off-the-shelf streaming app and player is a reasonable choice.
If you do need them to be in your app, however, you will have to look into MediaRecorder API (for the server/camera app) and MediaPlayer (for client/player app).
Quick sample code for the server:
// this is your network socket
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mCamera = getCameraInstance();
mMediaRecorder = new MediaRecorder();
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// this is the unofficially supported MPEG2TS format, suitable for streaming (Android 3.0+)
mMediaRecorder.setOutputFormat(8);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
mediaRecorder.setOutputFile(pfd.getFileDescriptor());
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
mMediaRecorder.prepare();
mMediaRecorder.start();
On the player side it is a bit tricky, you could try this:
// this is your network socket, connected to the server
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(pfd.getFileDescriptor());
mMediaPlayer.prepare();
mMediaPlayer.start();
Unfortunately mediaplayer tends to not like this, so you have a couple of options: either (a) save data from socket to file and (after you have a bit of data) play with mediaplayer from file, or (b) make a tiny http proxy that runs locally and can accept mediaplayer's GET request, reply with HTTP headers, and then copy data from the remote server to it. For (a) you would create the mediaplayer with a file path or file url, for (b) give it a http url pointing to your proxy.
See also:
Check this fiddle. You are going to need to take a look at using border-collapse and border-spacing. There are some quirks for IE (as usual). This is based on an answer to this question.
table.test td {
background-color: lime;
margin: 12px 12px 12px 12px;
padding: 12px 12px 12px 12px;
}
table.test {
border-collapse: separate;
border-spacing: 10px;
*border-collapse: expression('separate', cellSpacing='10px');
}
_x000D_
<table class="test">
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
</table>
_x000D_
It is explained here http://erabhinavrana.blogspot.in/2014/01/how-to-execute-update-query-by-applying.html
It also has other useful code snippets which are commonly used.
update <dbname of 1st table>.<table name of 1st table> A INNER JOIN <dbname of 2nd table>.<table name of 2nd table> RA ON A.<field name of table 1>=RA.<field name of table 2> SET A.<field name of table 1 to be updated>=RA.<field name of table 2 to set value in table 1>
Replace data in <>
with your appropriate values.
That's It. source:
//ICO , DI ,10 years back , this was they way:
public class AuditDAOImpl implements Audit{
//dependency
AuditDAO auditDAO = null;
//Control of the AuditDAO is with AuditDAOImpl because its creating the object
public AuditDAOImpl () {
this.auditDAO = new AuditDAO ();
}
}
Now with Spring 3,4 or latest its like below
public class AuditDAOImpl implements Audit{
//dependency
//Now control is shifted to Spring. Container find the object and provide it.
@Autowired
AuditDAO auditDAO = null;
}
Overall the control is inverted from old concept of coupled code to the frameworks like Spring which makes the object available. So that's IOC as far as I know and Dependency injection as you know when we inject the dependent object into another object using Constructor or setters . Inject basically means passing it as an argument. In spring we have XML & annotation based configuration where we define bean object and pass the dependent object with Constructor or setter injection style.
echo '2-1' |sudo tee /sys/bus/usb/drivers/usb/unbind
works for ubuntu
I am using the following
....
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<finalName>${project.groupId}/${project.artifactId}-${baseVersion}.${monthlyVersion}.${instanceVersion}</finalName>
</configuration>
</plugin>
....
This way you can define each value individually or pragmatically from Jenkins of some other system.
mvn package -DbaseVersion=1 -monthlyVersion=2 -instanceVersion=3
This will place a folder target\{group.id}\projectName-1.2.3.jar
A better way to save time might be
....
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<finalName>${project.groupId}/${project.artifactId}-${baseVersion}</finalName>
</configuration>
</plugin>
....
Like the same except I use on variable.
mvn package -DbaseVersion=0.3.4
This will place a folder target\{group.id}\projectName-1.2.3.jar
you can also use outputDirectory
inside of configuration
to specify a location you may want the package to be located.
If you are producing the entire output yourself, you can use sprintf()
, e.g.
> sprintf("%.10f",0.25)
[1] "0.2500000000"
specifies that you want to format a floating point number with ten decimal points (in %.10f
the f
is for float and the .10
specifies ten decimal points).
I don't know of any way of forcing R's higher level functions to print an exact number of digits.
Displaying 100 digits does not make sense if you are printing R's usual numbers, since the best accuracy you can get using 64-bit doubles is around 16 decimal digits (look at .Machine$double.eps on your system). The remaining digits will just be junk.
Tested on WinXP, Python 2.6 (3.x also tested) after installing pywin32 (pywin32-214.win32-py2.6.exe in my case):
import win32api, win32con
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
click(10,10)
In addition what others mentioned here, note that combining the Application.DispatcherUnhandledException
(and its similars) with
<configuration>
<runtime>
<legacyUnhandledExceptionPolicy enabled="1" />
</runtime>
</configuration>
in the app.config
will prevent your secondary threads exception from shutting down the application.
Just finished up a js library for formatting numbers Numeral.js. It handles decimals, dollars, percentages and even time formatting.
"fnInitComplete": function() {
$("#datatables4_wrapper").css("width","60%");
}
This worked fine to adjust the whole table width. Thanks @Peter Drinnan!
This looks like a prime candidate for separating the presentation from the data model. In this case, your preferences should be stored in a separate class that fires event updates whenever a particular property changes (look into INotifyPropertyChanged if your properties are a discrete set, or into a single event if they are more free-form text-based keys).
In your tree view, you'll make the changes to your preferences model, it will then fire an event. In your other forms, you'll subscribe to the changes that you're interested in. In the event handler you use to subscribe to the property changes, you use this.InvokeRequired to see if you are on the right thread to make the UI call, if not, then use this.BeginInvoke to call the desired method to update the form.
It is just as simple as this.....
//import java.io.FileInputStream;
//import java.io.FileInputStream;
Properties prop = new Properties();
//c:\\myapp\\config.ini is the location of the ini file
//ini file should look like host=localhost
prop.load(new FileInputStream("c:\\myapp\\config.ini"));
String host = prop.getProperty("host");
Inspired by the other answers here, I created an SQL function to do a sequence migration. The function moves a primary key sequence to a new contiguous sequence starting with any value (>= 1) either inside or outside the existing sequence range.
I explain here how I used this function in a migration of two databases with the same schema but different values into one database.
First, the function (which prints the generated SQL commands so that it is clear what is actually happening):
CREATE OR REPLACE FUNCTION migrate_pkey_sequence
( arg_table text
, arg_column text
, arg_sequence text
, arg_next_value bigint -- Must be >= 1
)
RETURNS int AS $$
DECLARE
result int;
curr_value bigint = arg_next_value - 1;
update_column1 text := format
( 'UPDATE %I SET %I = nextval(%L) + %s'
, arg_table
, arg_column
, arg_sequence
, curr_value
);
alter_sequence text := format
( 'ALTER SEQUENCE %I RESTART WITH %s'
, arg_sequence
, arg_next_value
);
update_column2 text := format
( 'UPDATE %I SET %I = DEFAULT'
, arg_table
, arg_column
);
select_max_column text := format
( 'SELECT coalesce(max(%I), %s) + 1 AS nextval FROM %I'
, arg_column
, curr_value
, arg_table
);
BEGIN
-- Print the SQL command before executing it.
RAISE INFO '%', update_column1;
EXECUTE update_column1;
RAISE INFO '%', alter_sequence;
EXECUTE alter_sequence;
RAISE INFO '%', update_column2;
EXECUTE update_column2;
EXECUTE select_max_column INTO result;
RETURN result;
END $$ LANGUAGE plpgsql;
The function migrate_pkey_sequence
takes the following arguments:
arg_table
: table name (e.g. 'example'
)arg_column
: primary key column name (e.g. 'id'
)arg_sequence
: sequence name (e.g. 'example_id_seq'
)arg_next_value
: next value for the column after migrationIt performs the following operations:
nextval('example_id_seq')
follows max(id)
and that the sequence starts
with 1. This also handles the case where arg_next_value > max(id)
.arg_next_value
. The order of key values are preserved but holes in the
range are not preserved.To demonstrate, we use a sequence and table defined as follows (e.g. using psql
):
# CREATE SEQUENCE example_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
# CREATE TABLE example
( id bigint NOT NULL DEFAULT nextval('example_id_seq'::regclass)
);
Then, we insert some values (starting, for example, at 3):
# ALTER SEQUENCE example_id_seq RESTART WITH 3;
# INSERT INTO example VALUES (DEFAULT), (DEFAULT), (DEFAULT);
-- id: 3, 4, 5
Finally, we migrate the example.id
values to start with 1.
# SELECT migrate_pkey_sequence('example', 'id', 'example_id_seq', 1);
INFO: 00000: UPDATE example SET id = nextval('example_id_seq') + 0
INFO: 00000: ALTER SEQUENCE example_id_seq RESTART WITH 1
INFO: 00000: UPDATE example SET id = DEFAULT
migrate_pkey_sequence
-----------------------
4
(1 row)
The result:
# SELECT * FROM example;
id
----
1
2
3
(3 rows)
Also, every link clicked with a target value of _new will replace the page loaded in the previously spawned window.
You can click here When to use _blank or _new to try it out for yourself.
This looks like a formating issue to me.
As far as SQL Server's money type is concerned 0 == 0.00
If you're trying to display 0 in say c# rather then 0.00 you should convert it to a string, and format it as you want. (or truncate it.)
Shallow copy with copy.copy()
#!/usr/bin/env python3
import copy
class C():
def __init__(self):
self.x = [1]
self.y = [2]
# It copies.
c = C()
d = copy.copy(c)
d.x = [3]
assert c.x == [1]
assert d.x == [3]
# It's shallow.
c = C()
d = copy.copy(c)
d.x[0] = 3
assert c.x == [3]
assert d.x == [3]
Deep copy with copy.deepcopy()
#!/usr/bin/env python3
import copy
class C():
def __init__(self):
self.x = [1]
self.y = [2]
c = C()
d = copy.deepcopy(c)
d.x[0] = 3
assert c.x == [1]
assert d.x == [3]
Documentation: https://docs.python.org/3/library/copy.html
Tested on Python 3.6.5.
you could try
$('*').not('#div').bind('touchmove', false);
add this if necessary
$('#div').bind('touchmove');
note that everything is fixed except #div
The simplest trick is to open the NIB file and do these two simple steps:
And the result:
There is yet an another way to add interceptors in your OkHttp3 (latest version as of now) , that is you add the interceptors to your Okhttp builder
okhttpBuilder.networkInterceptors().add(chain -> {
//todo add headers etc to your AuthorisedRequest
return chain.proceed(yourAuthorisedRequest);
});
and finally build your okHttpClient from this builder
OkHttpClient client = builder.build();
you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"')
,if you want to know more detail, please refer to $sce
imwrite(A,filename)
writes image data A to the file specified by filename, inferring the file format from the extension
You should put it into a function like this:
public static int toInt(byte[] bytes, int offset) {
int ret = 0;
for (int i=0; i<4 && i+offset<bytes.length; i++) {
ret <<= 8;
ret |= (int)bytes[i] & 0xFF;
}
return ret;
}
Example:
byte[] bytes = new byte[]{-2, -4, -8, -16};
System.out.println(Integer.toBinaryString(toInt(bytes, 0)));
Output:
11111110111111001111100011110000
This takes care of running out of bytes and correctly handling negative byte values.
I'm unaware of a standard function for doing this.
Issues to consider:
Endianness: different CPU architectures put the bytes that make up an int in different orders. Depending on how you come up with the byte array to begin with you may have to worry about this; and
Buffering: if you grab 1024 bytes at a time and start a sequence at element 1022 you will hit the end of the buffer before you get 4 bytes. It's probably better to use some form of buffered input stream that does the buffered automatically so you can just use readByte()
repeatedly and not worry about it otherwise;
Trailing Buffer: the end of the input may be an uneven number of bytes (not a multiple of 4 specifically) depending on the source. But if you create the input to begin with and being a multiple of 4 is "guaranteed" (or at least a precondition) you may not need to concern yourself with it.
to further elaborate on the point of buffering, consider the BufferedInputStream
:
InputStream in = new BufferedInputStream(new FileInputStream(file), 1024);
Now you have an InputStream
that automatically buffers 1024 bytes at a time, which is a lot less awkward to deal with. This way you can happily read 4 bytes at a time and not worry about too much I/O.
Secondly you can also use DataInputStream
:
InputStream in = new DataInputStream(new BufferedInputStream(
new FileInputStream(file), 1024));
byte b = in.readByte();
or even:
int i = in.readInt();
and not worry about constructing int
s at all.
Update April 2013: Don't do this. It wasn't a good idea in 2009 when I first answered the question and it really isn't a good idea now. See this answer by hackbod for reasons:
Avoid reloading activity with asynctask on orientation change in android
Add android:configChanges="keyboardHidden|orientation"
to your AndroidManifest.xml. This tells the system what configuration changes you are going to handle yourself - in this case by doing nothing.
<activity android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">
See Developer reference configChanges for more details.
However, your application can be interrupted at any time, e.g. by a phone call, so you really should add code to save the state of your application when it is paused.
Update: As of Android 3.2, you also need to add "screenSize":
<activity
android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
From Developer guide Handling the Configuration Change Yourself
Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must declare
android:configChanges="orientation|screenSize"
. However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).
UPDATE: (5 years later)
Note: If you decide to use Kappa Architecture (Event Sourcing + CQRS), then you do not need updated date at all. Since your data is an immutable, append-only event log, you only ever need event created date. Similar to the Lambda Architecture, described below. Then your application state is a projection of the event log (derived data). If you receive a subsequent event about existing entity, then you'll use that event's created date as updated date for your entity. This is a commonly used (and commonly misunderstood) practice in miceroservice systems.
UPDATE: (4 years later)
If you use ObjectId
as your _id
field (which is usually the case), then all you need to do is:
let document = {
updatedAt: new Date(),
}
Check my original answer below on how to get the created timestamp from the _id
field.
If you need to use IDs from external system, then check Roman Rhrn Nesterov's answer.
UPDATE: (2.5 years later)
You can now use the #timestamps option with mongoose version >= 4.0.
let ItemSchema = new Schema({
name: { type: String, required: true, trim: true }
},
{
timestamps: true
});
If set timestamps, mongoose assigns createdAt
and updatedAt
fields to your schema, the type assigned is Date
.
You can also specify the timestamp fileds' names:
timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }
Note: If you are working on a big application with critical data you should reconsider updating your documents. I would advise you to work with immutable, append-only data (lambda architecture). What this means is that you only ever allow inserts. Updates and deletes should not be allowed! If you would like to "delete" a record, you could easily insert a new version of the document with some
timestamp
/version
filed and then set adeleted
field totrue
. Similarly if you want to update a document – you create a new one with the appropriate fields updated and the rest of the fields copied over.Then in order to query this document you would get the one with the newest timestamp or the highest version which is not "deleted" (thedeleted
field is undefined or false`).Data immutability ensures that your data is debuggable – you can trace the history of every document. You can also rollback to previous version of a document if something goes wrong. If you go with such an architecture
ObjectId.getTimestamp()
is all you need, and it is not Mongoose dependent.
ORIGINAL ANSWER:
If you are using ObjectId as your identity field you don't need created_at
field. ObjectIds have a method called getTimestamp()
.
ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp()
This will return the following output:
ISODate("2012-10-15T21:26:17Z")
More info here How do I extract the created date out of a Mongo ObjectID
In order to add updated_at
filed you need to use this:
var ArticleSchema = new Schema({
updated_at: { type: Date }
// rest of the fields go here
});
ArticleSchema.pre('save', function(next) {
this.updated_at = Date.now();
next();
});
Same situation: Having done multiple Angular projects and moving to React, not having a simple way to provide services through DI seems like a missing piece (the particulars of the service aside).
Using context and ES7 decorators we can come close:
https://jaysoo.ca/2015/06/09/react-contexts-and-dependency-injection/
Seems these guys have taken it a step further / in a different direction:
http://blog.wolksoftware.com/dependency-injection-in-react-powered-inversifyjs
Still feels like working against the grain. Will revisit this answer in 6 months time after undertaking a major React project.
EDIT: Back 6 months later with some more React experience. Consider the nature of the logic:
Some also reach for HOCs for reuse but for me the above covers almost all use cases. Also, consider scaling state management using ducks to keep concerns separate and state UI-centric.
Function to hide the keyboard.
public static void hideKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
Hide keyboard in AndroidManifext.xml file.
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:windowSoftInputMode="stateHidden">
There is no runtime performance cost to using var. Though, I would suspect there to be a compiling performance cost as the compiler needs to infer the type, though this will most likely be negligable.
<div id="uploadButton">UPLOAD</div>
<form action="[FILE_HANDLER_URL]" style="display:none">
<input id="myInput" type="file" />
</form>
<script>
const uploadButton = document.getElementById('uploadButton');
const myInput = document.getElementById('myInput');
uploadButton.addEventListener('click', () => {
myInput.click();
});
</script>
Yes it is possible in Sony ericssion xylophone w20 .I have got this phone in 2010.but yet this type of phone I have not seen.
You can use JS as below:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('elementid').focus();");
Off hand the code looks right. What if you try using an 'Else' and see what happens?
IF @SchoolCategoryCode = 'Elem'
--- We now have determined we are processing an elementary school...
BEGIN
---- Only do the following if the variable @Term equals a 3 - if it does not, skip just this first part
IF @Term = 3
BEGIN
INSERT INTO @Classes
SELECT
XXXXXX
FROM XXXX blah blah blah
INSERT INTO @Classes
SELECT
XXXXXXXX
FROM XXXXXX (more code)
END <----(Should this be ENDIF?)
ELSE
BEGIN
INSERT INTO @Classes
SELECT
XXXXXXXX
FROM XXXXXX (more code)
END
END
if you are using target sdk as 23 add below code in your build.gradle
android{
useLibrary 'org.apache.http.legacy'
}
additional note here: dont try using the gradle versions of those files. they are broken (28.08.15). I tried over 5 hours to get it to work. it just doesnt. not working:
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
another thing dont use:
'org.apache.httpcomponents:httpclient-android:4.3.5.1'
its referring 21 api level.
For anybody who will come upon this problem and they tried all that was suggested and nothing still works, this is how I sorted my problem, instead of doing LocalBroadcastManager.getInstance(this).registerReceiver(...)
I first created a local variable of type LocalBroadcastManager,
private LocalBroadcastManager lbman;
And used this variable to carry out the registering and unregistering on the broadcastreceiver, that is
lbman.registerReceiver(bReceiver);
and
lbman.unregisterReceiver(bReceiver);
If using reactive forms, you can also disable the entire form or any sub-set of controls in a FormGroup with myFormGroup.disable()
.
To access SQL via the command line we simply navigate to the xampp folder. the folder is usually on the c:\ drive.
in mysql -u root -p
then press enter.use cms_data
or any other db_name, it should say Database changed// Bonus Note you shouldn't use the root user when working with databases. you would want to create a separate account (ex. cms_user) with special privileges to limit errors.
to do that type:
GRANT ALL PRIVILEGES IN cms_database.*
TO 'cms_user'@'localhost'
IDENTITIED BY 'yourpassword'
double check by using the command:
SHOW GRANT FOR 'cms_user'@localhost;
if you already have the name of the user and the specific database you wish to use, change step 2 to this.
mysql -u cms_user -p cms_database
Apply this code in your css
::-webkit-scrollbar{
-webkit-appearance: none;
width: 7px;
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(0,0,0,.5);
-webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}
Even later to the party.
function zfill(num, len) {
return(0 > num ? "-" : "") + (Math.pow(10, len) <= Math.abs(num) ? "0" + Math.abs(num) : Math.pow(10, len) + Math.abs(num)).toString().substr(1)
}
This handles negatives and situations where the number is longer than the field width. And floating-point.
It is naming convention used when passing callbacks in situations that require serial execution of actions, e.g. scan directory -> read file data -> do something with data. This is in preference to deeply nesting the callbacks. The first three sections of the following article on Tim Caswell's HowToNode blog give a good overview of this:
http://howtonode.org/control-flow
Also see the Sequential Actions section of the second part of that posting:
In case of a 2D array (matrix), you can use:
[val, idx] = max(A, [], 2);
The idx part will contain the column number of containing the max element of each row.
You can use _.indexOf method or if you don't want to include whole Underscore.js library in your app, you can have a look how they did it and extract necessary code.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, l = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < l; i++) if (array[i] === item) return i;
return -1;
};
Escape the apostrophe in O'Neal
by writing O''Neal
(two apostrophes).
To extend @Dave's answer...if planRec.approved_by is already a string
this.approved_by = planRec.approved_by ?? "";
UPDATE:
compile 'com.android.volley:volley:1.0.0'
OLD ANSWER: You need the next in your build.gradle of your app module:
dependencies {
compile 'com.mcxiaoke.volley:library:1.0.19'
(Rest of your dependencies)
}
This is not the official repo but is a highly trusted one.
A specification (blueprint) about how to make an OS compatible with late UNIX OS (may God bless him!). This is why macOS and GNU/Linux have very similar terminal command lines, GUI's, libraries, etc. Because they both were designed according to POSIX blueprint.
POSIX does not tell engineers and programmers how to code but what to code.
# Let's add key:value to a dictionary, the functional way
# Create your dictionary class
class my_dictionary(dict):
# __init__ function
def __init__(self):
self = dict()
# Function to add key:value
def add(self, key, value):
self[key] = value
# Main Function
dict_obj = my_dictionary()
limit = int(input("Enter the no of key value pair in a dictionary"))
c=0
while c < limit :
dict_obj.key = input("Enter the key: ")
dict_obj.value = input("Enter the value: ")
dict_obj.add(dict_obj.key, dict_obj.value)
c += 1
print(dict_obj)
To achieve this feat, define a outer linear layout with a weightSum={amount of weight to distribute}
.
it defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.Another example would be set weightSum=2, and if the two children set layout_weight=1
then each would get 50% of the available space.
WeightSum is dependent on the amount of children in the parent layout.
I don't see a way to run a single untagged test within a test class but I am providing my workflow since it seems to be useful for anyone who runs into this question.
From within a sbt session:
test:testOnly *YourTestClass
(The asterisk is a wildcard, you could specify the full path com.example.specs.YourTestClass
.)
All tests within that test class will be executed. Presumably you're most concerned with failing tests, so correct any failing implementations and then run:
test:testQuick
... which will only execute tests that failed. (Repeating the most recently executed test:testOnly
command will be the same as test:testQuick
in this case, but if you break up your test methods into appropriate test classes you can use a wildcard to make test:testQuick
a more efficient way to re-run failing tests.)
Note that the nomenclature for test in ScalaTest is a test class, not a specific test method, so all untagged methods are executed.
If you have too many test methods in a test class break them up into separate classes or tag them appropriately. (This could be a signal that the class under test is in violation of single responsibility principle and could use a refactoring.)
I'm using Batik for this. The complete Delphi code:
procedure ExecNewProcess(ProgramName : String; Wait: Boolean);
var
StartInfo : TStartupInfo;
ProcInfo : TProcessInformation;
CreateOK : Boolean;
begin
FillChar(StartInfo, SizeOf(TStartupInfo), #0);
FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
StartInfo.cb := SizeOf(TStartupInfo);
CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False,
CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS,
nil, nil, StartInfo, ProcInfo);
if CreateOK then begin
//may or may not be needed. Usually wait for child processes
if Wait then
WaitForSingleObject(ProcInfo.hProcess, INFINITE);
end else
ShowMessage('Unable to run ' + ProgramName);
CloseHandle(ProcInfo.hProcess);
CloseHandle(ProcInfo.hThread);
end;
procedure ConvertSVGtoPNG(aFilename: String);
const
ExecLine = 'c:\windows\system32\java.exe -jar C:\Apps\batik-1.7\batik-rasterizer.jar ';
begin
ExecNewProcess(ExecLine + aFilename, True);
end;
Swift 3, dictionary extension:
public extension Dictionary {
public static func +=(lhs: inout Dictionary, rhs: Dictionary) {
for (k, v) in rhs {
lhs[k] = v
}
}
}
A great Spring MVC quickstart archetype is available on GitHub, courtesy of kolorobot. Good instructions are provided on how to install it to your local Maven repo and use it to create a new Spring MVC project. He’s even helpfully included the Tomcat 7 Maven plugin in the archetypical project so that the newly created Spring MVC can be run from the command line without having to manually deploy it to an application server.
Kolorobot’s example application includes the following:
For me the fix was removing the node* packages and also the npm packages.
Then a fresh install as:
sudo apt-get install autoclean
sudo apt-get install nodejs-legacy
npm install
simple 2 line jquery to strip the html.
var content = "<p>checking the html source </p><p>
</p><p>with </p><p>all</p><p>the html </p><p>content</p>";
var text = $(content).text();//It gets you the plain text
console.log(text);//check the data in your console
cj("#text_area_id").val(text);//set your content to text area using text_area_id
MyTabControl.SelectedTab.Enabled = false;
Simple:
public int getArrayIndex(int[] arr,int value) {
for(int i=0;i<arr.length;i++)
if(arr[i]==value) return i;
return -1;
}
You can also use MyGeneration (free tool) to write your own sql generated scripts. There is a "insert into" script for SQL Server included in MyGeneration, which can be easily changed to run under Oracle.
Try following code. It is working for me....
UPDATE TableOne
SET
field1 =(SELECT TableTwo.field1 FROM TableTwo WHERE TableOne.id=TableTwo.id),
field2 =(SELECT TableTwo.field2 FROM TableTwo WHERE TableOne.id=TableTwo.id)
WHERE TableOne.id = (SELECT TableTwo.id
FROM TableTwo
WHERE TableOne.id = TableTwo.id)
I used this way to take the last record for each user that I have on my table. It was a query to get last location for salesman as per recent time detected on PDA devices.
CREATE FUNCTION dbo.UsersLocation()
RETURNS TABLE
AS
RETURN
Select GS.UserID, MAX(GS.UTCDateTime) 'LastDate'
From USERGPS GS
where year(GS.UTCDateTime) = YEAR(GETDATE())
Group By GS.UserID
GO
select gs.UserID, sl.LastDate, gs.Latitude , gs.Longitude
from USERGPS gs
inner join USER s on gs.SalesManNo = s.SalesmanNo
inner join dbo.UsersLocation() sl on gs.UserID= sl.UserID and gs.UTCDateTime = sl.LastDate
order by LastDate desc
Specifying a flex attribute to the container worked for me:
.container {
flex: 0 0 auto;
}
This ensures the height is set and doesn't grow either.
I usually add to index changes I don't want to stash and then stash with --keep-index
option.
git add app/controllers/cart_controller.php
git stash --keep-index
git reset
Last step is optional, but usually you want it. It removes changes from index.
Warning
As noted in the comments, this puts everything into the stash, both staged and unstaged. The --keep-index
just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.
Let's suppose you have a book, probably a novel, a thick one with lots of things to read, hence lots of words. Now, hypothetically, you brought two dictionaries, consisting of only words that are only used, at least one time in the novel. All words in that two dictionaries are stored in typical alphabetical order. In hypothetical dictionary A, words are printed only once while in hypothetical dictionary B words are printed as many numbers of times it is printed in the novel. Remember, words are sorted alphabetically in both the dictionaries. Now you got stuck at some point while reading a novel and need to find the meaning of that word from anyone of those hypothetical dictionaries. What you will do? Surely you will jump to that word in a few steps to find its meaning, rather look for the meaning of each of the words in the novel, from starting, until you reach that bugging word.
This is how the index works in SQL. Consider Dictionary A as PRIMARY INDEX, Dictionary B as KEY/SECONDARY INDEX, and your desire to get for the meaning of the word as a QUERY/SELECT STATEMENT. The index will help to fetch the data at a very fast rate. Without an index, you will have to look for the data from the starting, unnecessarily time-consuming costly task.
For more about indexes and types, look this.
The problem is that tick()
needs to know the definition of tile_tree_apple
, but all it has is a forward declaration of it. You should separate the declarations and definitions like so:
tile_tree.h
#ifndef TILE_TREE_H
#define TILE_TREE_H
#include "tile.h"
class tile_tree : public tile
{
public:
tile onDestroy();
tile tick();
void onCreate();
};
#endif
tile_tree.cpp
:
tile tile_tree::onDestroy() {
return *new tile_grass;
}
tile tile_tree::tick() {
if (rand() % 20 == 0)
return *new tile_tree_apple;
}
void tile_tree::onCreate() {
health = rand() % 5 + 4;
type = TILET_TREE;
}
Except you have a major problem: you’re allocating memory (with new
), then copying the allocated object and returning the copy. This is called a memory leak, because there’s no way for your program to free the memory it uses. Not only that, but you’re copying a tile_tree
into a tile
, which discards the information that makes a tile_tree
different from a tile
; this is called slicing.
What you want is to return a pointer to a new tile
, and make sure you call delete
at some point to free the memory:
tile* tile_tree::tick() {
if (rand() % 20 == 0)
return new tile_tree_apple;
}
Even better would be to return a smart pointer that will handle the memory management for you:
#include <memory>
std::shared_ptr<tile> tile_tree::tick() {
if (rand() % 20 == 0)
return std::make_shared<tile_tree_apple>();
}
It's simple
y = [['vegas','London'],['US','UK']]
for x in y:
for a in x:
print(a)
If all you are trying to do is capture the output from a command, then this will work well.
I use it for changing system time, as [timezoneinfo]::local
always produces the same information, even after you have made changes to the system. This is the only way I can validate and log the change in time zone:
$NewTime = (powershell.exe -command [timezoneinfo]::local)
$NewTime | Tee-Object -FilePath $strLFpath\$strLFName -Append
Meaning that I have to open a new PowerShell session to reload the system variables.
In ActivityOne,
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putExtra("data", somedata);
startActivity(intent);
In ActivityTwo,
Intent intent = getIntent();
String data = intent.getStringExtra("data");
From the Help:
Set isect = Application.Intersect(Range("rg1"), Range("rg2"))
If isect Is Nothing Then
MsgBox "Ranges do not intersect"
Else
isect.Select
End If
You can also put the JavaScript code in script tags, rather than a separate function. <script>//JS Code</script>
This way the code will get executes on Page Load.
Add double quotes to use caret operator in version number.
composer require middlewares/whoops "^0.4"
Syntax
DATEDIFF(expr1,expr2)
Description
DATEDIFF() returns (expr1 – expr2) expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.
@D Stanley
This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)
char *words; // setting this to NULL would have prevented the issue
if (condition) {
words = malloc( 512 );
/* calling free sometime later works here */
free(words)
} else {
/* do not allocate words in this branch */
}
/* free(words); -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/
There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:
*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer
IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.
If you want to change the session id on each log in, make sure to use session_regenerate_id(true) during the log in process.
<?php
session_start();
session_regenerate_id(true);
?>
I was looking for a solution to enumerate an array of an unknown at compile time rank with an access to every element indices set. I saw solutions with yield but here is another implementation with no yield. It is in old school minimalistic way. In this example AppendArrayDebug() just prints all the elements into StringBuilder buffer.
public static void AppendArrayDebug ( StringBuilder sb, Array array )
{
if( array == null || array.Length == 0 )
{
sb.Append( "<nothing>" );
return;
}
int i;
var rank = array.Rank;
var lastIndex = rank - 1;
// Initialize indices and their boundaries
var indices = new int[rank];
var lower = new int[rank];
var upper = new int[rank];
for( i = 0; i < rank; ++i )
{
indices[i] = lower[i] = array.GetLowerBound( i );
upper[i] = array.GetUpperBound( i );
}
while( true )
{
BeginMainLoop:
// Begin work with an element
var element = array.GetValue( indices );
sb.AppendLine();
sb.Append( '[' );
for( i = 0; i < rank; ++i )
{
sb.Append( indices[i] );
sb.Append( ' ' );
}
sb.Length -= 1;
sb.Append( "] = " );
sb.Append( element );
// End work with the element
// Increment index set
// All indices except the first one are enumerated several times
for( i = lastIndex; i > 0; )
{
if( ++indices[i] <= upper[i] )
goto BeginMainLoop;
indices[i] = lower[i];
--i;
}
// Special case for the first index, it must be enumerated only once
if( ++indices[0] > upper[0] )
break;
}
}
For example the following array will produce the following output:
var array = new [,,]
{
{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } },
{ { 13, 14, 15 }, { 16, 17, 18 }, { 19, 20, 21 }, { 22, 23, 24 } }
};
/*
Output:
[0 0 0] = 1
[0 0 1] = 2
[0 0 2] = 3
[0 1 0] = 4
[0 1 1] = 5
[0 1 2] = 6
[0 2 0] = 7
[0 2 1] = 8
[0 2 2] = 9
[0 3 0] = 10
[0 3 1] = 11
[0 3 2] = 12
[1 0 0] = 13
[1 0 1] = 14
[1 0 2] = 15
[1 1 0] = 16
[1 1 1] = 17
[1 1 2] = 18
[1 2 0] = 19
[1 2 1] = 20
[1 2 2] = 21
[1 3 0] = 22
[1 3 1] = 23
[1 3 2] = 24
*/
Step-1: Your Model class
public class RechargeMobileViewModel
{
public string CustomerFullName { get; set; }
public string TelecomSubscriber { get; set; }
public int TotalAmount { get; set; }
public string MobileNumber { get; set; }
public int Month { get; set; }
public List<SelectListItem> getAllDaysList { get; set; }
// Define the list which you have to show in Drop down List
public List<SelectListItem> getAllWeekDaysList()
{
List<SelectListItem> myList = new List<SelectListItem>();
var data = new[]{
new SelectListItem{ Value="1",Text="Monday"},
new SelectListItem{ Value="2",Text="Tuesday"},
new SelectListItem{ Value="3",Text="Wednesday"},
new SelectListItem{ Value="4",Text="Thrusday"},
new SelectListItem{ Value="5",Text="Friday"},
new SelectListItem{ Value="6",Text="Saturday"},
new SelectListItem{ Value="7",Text="Sunday"},
};
myList = data.ToList();
return myList;
}
}
Step-2: Call this method to fill Drop down in your controller Action
namespace MvcVariousApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
RechargeMobileViewModel objModel = new RechargeMobileViewModel();
objModel.getAllDaysList = objModel.getAllWeekDaysList();
return View(objModel);
}
}
}
Step-3: Fill your Drop-Down List of View as follows
@model MvcVariousApplication.Models.RechargeMobileViewModel
@{
ViewBag.Title = "Contact";
}
@Html.LabelFor(model=> model.CustomerFullName)
@Html.TextBoxFor(model => model.CustomerFullName)
@Html.LabelFor(model => model.MobileNumber)
@Html.TextBoxFor(model => model.MobileNumber)
@Html.LabelFor(model => model.TelecomSubscriber)
@Html.TextBoxFor(model => model.TelecomSubscriber)
@Html.LabelFor(model => model.TotalAmount)
@Html.TextBoxFor(model => model.TotalAmount)
@Html.LabelFor(model => model.Month)
@Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")
You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
If the customer does not exist, you'll get an sql exception which text will be something like:
null value in column "customer_id" violates not-null constraint
(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:
insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.
Send as many inserts across the wire at one time as possible. The actual insert speed should be the same, but you will see performance gains from the reduction of network overhead.
Or try this one. For me it's working fine:
imageView.setImageDrawable(ContextCompat.getDrawable(this, image));
First change the following parameters:
Tools -> Options -> Debugging -> Symbols -> Server -> Yes
Then press Ctrl+F5 and you will see amazing things.
Use a delimiter to separate the values.
<select name="myValues">
<option value="one|two">
</select>
<?php>
$value = filter_input(INPUT_POST, 'myValues');
$exploded_value = explode('|', $value);
$value_one = $exploded_value[0];
$value_two = $exploded_value[1];
?>
The Tag is just used to easily find your output, because the Output of LogCat can be sometimes very long. You can define somewhere in your class:
private static final String TAG = "myApp";
and use it when debugging
Log.v(TAG, "did something");
You can apply as well a Filter to only search for the tag.
There is actually a truly invisible character: U+FEFF
.
This character is called the Byte Order Mark and is related to the Unicode 8 system. It is a really confusing concept that can be explained HERE The Byte Order Mark or BOM
for short is an invisible character that doesn't take up any space. You can copy the character bellow between the >
and <
.
Here is the character:
> <
How to catch this character in action:
>
and <
,You will notice that when your caret gets to the place you pasted the character, it will briefly stop for around half a second. This is becuase the caret is passing over the invisible character. Even though you can't see it doesn't mean it isn't there. The caret still sees that there is a character in that area that you pasted the BOM and will pass through it. Since the BOM is invisble, the caret will look like it has paused for a brief moment. You can past the BOM multiple times in an area and redo the steps above to really show the affect. Good luck!
EDIT: Sadly, Stackoverflow doesn't like the character. Here is an example from w3.org: https://www.w3.org/International/questions/examples/phpbomtest.php
If you are responsible for encoding the data in PHP using urlencode, PHP's rawurlencode works with JavaScript's decodeURIComponent without needing to replace the + character.
StreamSaver is an alternative to save very large files without having to keep all data in the memory.
In fact it emulates everything the server dose when saving a file but all client side with service worker.
You can either get the writer and manually write Uint8Array's to it or pipe a binary readableStream to the writable stream
There is a few example showcasing:
Response
or blob.stream()
to StreamSaverHere is an example in it's simplest form:
const fileStream = streamSaver.createWriteStream('filename.txt')
new Response('StreamSaver is awesome').body
.pipeTo(fileStream)
.then(success, error)
If you want to save a blob you would just convert that to a readableStream
new Response(blob).body.pipeTo(...) // response hack
blob.stream().pipeTo(...) // feature reference
I think you want something like this:
Intent foo = new Intent(this, viewContacts.class);
foo.putExtra("myFirstKey", "myFirstValue");
foo.putExtra("mySecondKey", "mySecondValue");
startActivity(foo);
or you can combine them into a bundle first. Corresponding getExtra() routines exist for the other side. See the intent topic in the dev guide for more information.
Declare the object like this.
export interface Thread {
id:number;
messageIds: number[];
participants: {
[key:number]: number
};
}
The simplest way to install jq
and test that it works is through brew and then using the simplest filter that merely formats the JSON
brew
is the easiest way to manage packages on a mac:
brew install jq
Need brew
? Run the following command:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Failing that: instructions to install and use are on https://brew.sh/
The .
filter takes its input and produces it unchanged as output. This is the identity operator. (quote the docs)
echo '{ "name":"John", "age":31, "city":"New York" }' | jq .
The result should appear like so in your terminal:
{
"name": "John",
"age": 31,
"city": "New York"
}
If you want to remove all -
you can use:
.replace(new RegExp('-', 'g'),"")
In bash 4, you can use associative arrays:
declare -A foo
foo[0]="bar"
foo[35]="baz"
for key in "${!foo[@]}"
do
echo "key: $key, value: ${foo[$key]}"
done
# output
# $ key: 0, value bar.
# $ key: 35, value baz.
In bash 3, this works (also works in zsh):
map=( )
map+=("0:bar")
map+=("35:baz")
for keyvalue in "${map[@]}" ; do
key=${keyvalue%%:*}
value=${keyvalue#*:}
echo "key: $key, value $value."
done
You can move to desired activity on button click. just add
android:onClick="timerApp"this line.
xml:
<Button
android:id="@+id/timer_app"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="timerApp"
android:text="Click To run Timer Activity" />
In your main activity just add this method:
public void timerApp(View view){
Intent intent= new Intent(MainActivity.this,TimerActivity.class);
startActivity(intent);
}
OR in onCreate() method add below code
Button btn =findViewById(R.id.timer_app);//Don't need to type casting in android studio 3
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, TimerActivity.class);
startActivity(intent);
}
});
Rocket's answer doesn't work.
<div>hhhhhh
<div>This is a test</div>
<div>Another Div</div>
</div>
I simply modified his DEMO here and you can see the root DOM is selected.
$('div:contains("test"):last').css('background-color', 'red');
add ":last" selector in the code to fix this.
The main reason you use the default queue over the main queue is to run tasks in the background.
For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
});
});
Close any open projects which are not in current use.
Try to switch off the auto publish mode during development.
You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.
$image
is in your case the value of the item and not the key. Use the following syntax to get the key too:
foreach ($images as $key => $value) {
/* … */
}
Now you can delete the item with unset($images[$key])
.
I have the same issue and I change any hostname that matches the local host name to 0.0.0.0, it seems to work after I do that.
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'
or simply this if you are sure that you have no values like this CKIT002
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
It looks like immediately after you draw the circle, you go into the main glut loop, where you've set the Draw()
function to draw every time through the loop. So it's probably drawing the circle, then erasing it immediately and drawing the square. You should probably either make DrawCircle()
your glutDisplayFunc()
, or call DrawCircle()
from Draw()
.
A variation on Greg’s answer that includes carriage returns too:
/[^\S\r\n]/
This regex is safer than /[^\S\n]/
with no \r
. My reasoning is that Windows uses \r\n
for newlines, and Mac OS 9 used \r
. You’re unlikely to find \r
without \n
nowadays, but if you do find it, it couldn’t mean anything but a newline. Thus, since \r
can mean a newline, we should exclude it too.
sc queryex <service name>
taskkill /F /PID <Service PID>
eg
If it's not the Home edition of XP, you can use \\servername\c$
Mark Brackett's comment:
Note that you need to be an Administrator on the local machine, as the share permissions are locked down
It would be fine to use query parameters on a POST endpoint, provided they refer to already existing resources.
For example:
POST /user_settings?user_id=4
{
"use_safe_mode": 1
}
The POST above has a query parameter referring to an existing resource. The body parameter defines the new resource to be created.
(Granted, this may be more of a personal preference than a dogmatic principle.)
i had to use it for a condition add if you don't need the index
using System.Linq;
use
if(list.Any(x => x.Title == title){
// do something here
}
this will tell you if any variable satisfies your given condition.
If anyone stumbles across this as it is the first result in google,
remember to specify the filename too in the SaveAs method.
Won't work
file_upload.PostedFile.SaveAs(Server.MapPath(SaveLocation));
You need this:
filename = Path.GetFileName(file_upload.PostedFile.FileName);
file_upload.PostedFile.SaveAs(Server.MapPath(SaveLocation + "\\" + filename));
I assumed the SaveAs method will automatically use the filename uploaded. Kept getting "Access denied" error. Not very descriptive of the actual problem
Code snippet above provides incorrect byte order in string, so I fixed it a bit.
char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B','C','D','E','F'};
std::string byte_2_str(char* bytes, int size) {
std::string str;
for (int i = 0; i < size; ++i) {
const char ch = bytes[i];
str.append(&hex[(ch & 0xF0) >> 4], 1);
str.append(&hex[ch & 0xF], 1);
}
return str;
}
Thank Mathias Lin, tested and it works!
In addition, sample implementation of Mathias's method in activity can be as follows.
public class DirectionMapActivity extends MapActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.directionmap);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String locationProvider = LocationManager.NETWORK_PROVIDER;
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");//from
urlString.append( Double.toString(lastKnownLocation.getLatitude() ));
urlString.append(",");
urlString.append( Double.toString(lastKnownLocation.getLongitude() ));
urlString.append("&daddr=");//to
urlString.append( Double.toString((double)dest[0]/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)dest[1]/1.0E6 ));
urlString.append("&ie=UTF8&0&om=0&output=kml");
try{
// setup the url
URL url = new URL(urlString.toString());
// create the factory
SAXParserFactory factory = SAXParserFactory.newInstance();
// create a parser
SAXParser parser = factory.newSAXParser();
// create the reader (scanner)
XMLReader xmlreader = parser.getXMLReader();
// instantiate our handler
NavigationSaxHandler navSaxHandler = new NavigationSaxHandler();
// assign our handler
xmlreader.setContentHandler(navSaxHandler);
// get our data via the url class
InputSource is = new InputSource(url.openStream());
// perform the synchronous parse
xmlreader.parse(is);
// get the results - should be a fully populated RSSFeed instance, or null on error
NavigationDataSet ds = navSaxHandler.getParsedData();
// draw path
drawPath(ds, Color.parseColor("#add331"), mapView );
// find boundary by using itemized overlay
GeoPoint destPoint = new GeoPoint(dest[0],dest[1]);
GeoPoint currentPoint = new GeoPoint( new Double(lastKnownLocation.getLatitude()*1E6).intValue()
,new Double(lastKnownLocation.getLongitude()*1E6).intValue() );
Drawable dot = this.getResources().getDrawable(R.drawable.pixel);
MapItemizedOverlay bgItemizedOverlay = new MapItemizedOverlay(dot,this);
OverlayItem currentPixel = new OverlayItem(destPoint, null, null );
OverlayItem destPixel = new OverlayItem(currentPoint, null, null );
bgItemizedOverlay.addOverlay(currentPixel);
bgItemizedOverlay.addOverlay(destPixel);
// center and zoom in the map
MapController mc = mapView.getController();
mc.zoomToSpan(bgItemizedOverlay.getLatSpanE6()*2,bgItemizedOverlay.getLonSpanE6()*2);
mc.animateTo(new GeoPoint(
(currentPoint.getLatitudeE6() + destPoint.getLatitudeE6()) / 2
, (currentPoint.getLongitudeE6() + destPoint.getLongitudeE6()) / 2));
} catch(Exception e) {
Log.d("DirectionMap","Exception parsing kml.");
}
}
// and the rest of the methods in activity, e.g. drawPath() etc...
MapItemizedOverlay.java
public class MapItemizedOverlay extends ItemizedOverlay{
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public MapItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
@Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
@Override
public int size() {
return mOverlays.size();
}
}
DataFrame.sort
is deprecated; use DataFrame.sort_values
.
>>> df.sort_values(['c1','c2'], ascending=[False,True])
c1 c2
0 3 10
3 2 15
1 2 30
4 2 100
2 1 20
>>> df.sort(['c1','c2'], ascending=[False,True])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ampawake/anaconda/envs/pseudo/lib/python2.7/site-packages/pandas/core/generic.py", line 3614, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'sort'
To handle One-To-Many relationships in Django you need to use ForeignKey
.
The documentation on ForeignKey is very comprehensive and should answer all the questions you have:
https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey
The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).
If you want the reverse relationship, you would need to add two ForeignKey fields to your PhoneNumber model, one to Dude and one to Business. This would allow each number to belong to either one Dude or one Business, and have Dudes and Businesses able to own multiple Numbers. I think this might be what you are after.
class Business(models.Model):
...
class Dude(models.Model):
...
class PhoneNumber(models.Model):
dude = models.ForeignKey(Dude)
business = models.ForeignKey(Business)
Some other things I found out:
You can't directly pass in an array like:
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xx",
"<script>test("+x+","+y+");</script>");
because that calls the ToString() methods of x and y, which returns "System.Int32[]", and obviously Javascript can't use that. I had to pass in the arrays as strings, like "[1,2,3,4,5]", so I wrote a helper method to do the conversion.
Also, there is a difference between this.Page.ClientScript.RegisterStartupScript() and this.Page.ClientScript.RegisterClientScriptBlock() - the former places the script at the bottom of the page, which I need in order to be able to access the controls (like with document.getElementByID). RegisterClientScriptBlock() is executed before the tags are rendered, so I actually get a Javascript error if I use that method.
http://www.wrox.com/WileyCDA/Section/Manipulating-ASP-NET-Pages-and-Server-Controls-with-JavaScript.id-310803.html covers the difference between the two pretty well.
Here's the complete example I came up with:
// code behind
protected void Button1_Click(object sender, EventArgs e)
{
int[] x = new int[] { 1, 2, 3, 4, 5 };
int[] y = new int[] { 1, 2, 3, 4, 5 };
string xStr = getArrayString(x); // converts {1,2,3,4,5} to [1,2,3,4,5]
string yStr = getArrayString(y);
string script = String.Format("test({0},{1})", xStr, yStr);
this.Page.ClientScript.RegisterStartupScript(this.GetType(),
"testFunction", script, true);
//this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
//"testFunction", script, true); // different result
}
private string getArrayString(int[] array)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.Length; i++)
{
sb.Append(array[i] + ",");
}
string arrayStr = string.Format("[{0}]", sb.ToString().TrimEnd(','));
return arrayStr;
}
//aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function test(x, y)
{
var text1 = document.getElementById("text1")
for(var i = 0; i<x.length; i++)
{
text1.innerText += x[i]; // prints 12345
}
text1.innerText += "\ny: " + y; // prints y: 1,2,3,4,5
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
</div>
<div id ="text1">
</div>
</form>
</body>
</html>
Other option is to use ArrayUtils.toArray in org.apache.commons.lang3
ArrayUtils.toArray("elem1","elem2")
To check if one or more columns all exist, you can use set.issubset
, as in:
if set(['A','C']).issubset(df.columns):
df['sum'] = df['A'] + df['C']
As @brianpck points out in a comment, set([])
can alternatively be constructed with curly braces,
if {'A', 'C'}.issubset(df.columns):
See this question for a discussion of the curly-braces syntax.
Or, you can use a list comprehension, as in:
if all([item in df.columns for item in ['A','C']]):
The following worked for me: Just save as custom_shape.xml.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- "shadow" -->
<item>
<shape android:shape="rectangle" >
<solid android:color="#000000"/>
<corners android:radius="12dp" />
</shape>
</item>
<item android:bottom="3px">
<shape android:shape="rectangle">
<solid android:color="#90ffffff"/>
<corners android:radius="12dp" />
</shape>
</item>
</layer-list>
This is a slight variation, but PJW's solution didn't quite work for me:
java -version 2>&1 | head -n 1 | cut -d'"' -f2
just cut the string on the delimiter "
(double quotes) and get the second field.
Exact implementation of Environment.NewLine
from the source code:
The implementation in .NET 4.6.1:
/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the given
** platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
get {
Contract.Ensures(Contract.Result<String>() != null);
return "\r\n";
}
}
The implementation in .NET Core:
/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the
** given platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
get {
Contract.Ensures(Contract.Result() != null);
#if !PLATFORM_UNIX
return "\r\n";
#else
return "\n";
#endif // !PLATFORM_UNIX
}
}
source (in System.Private.CoreLib
)
public static string NewLine => "\r\n";
source (in System.Runtime.Extensions
)
Lets say I want to start the service on an event - onItemClicked() of a button. The Receiver mechanism would not work in that case because :-
a) I passed the Receiver to the service (as in Intent extra) from onItemClicked()
b) Activity moves to the background. In onPause() I set the receiver reference within the ResultReceiver to null to avoid leaking the Activity.
c) Activity gets destroyed.
d) Activity gets created again. However at this point the Service will not be able to make a callback to the Activity as that receiver reference is lost.
The mechanism of a limited broadcast or a PendingIntent seems to be more usefull in such scenarios- refer to Notify activity from service
You have to override your ;
delimiter with something like $$
to avoid this kind of error.
After your function definition, you can set the delimiter back to ;
.
This should work:
DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal)
RETURNS decimal
DETERMINISTIC
BEGIN
DECLARE dist decimal;
SET dist = SQRT(x1 - y1);
RETURN dist;
END$$
DELIMITER ;
Place the following in your jQuery mouseover
event handler:
$(this).css('color', 'red');
To set both color and size at the same time:
$(this).css({ 'color': 'red', 'font-size': '150%' });
You can set any CSS attribute using the .css()
jQuery function.
Its because you have no BEGIN
and END
statements. You shouldn't be seeing the prints, or errors running this statement, only Statement Completed
(or something like that).
Could not find a declaration file for module 'busboy'. 'f:/firebase-cloud-
functions/functions/node_modules/busboy/lib/main.js' implicitly has an ‘any’
type.
Try `npm install @types/busboy` if it exists or add a new declaration (.d.ts)
the file containing `declare module 'busboy';`
In my case it's solved: All you have to do is edit your TypeScript Config file (tsconfig.json
) and add a new key-value pair as:
"noImplicitAny": false
In Swift 3.0 you can get the appdelegate
reference by
let appDelegate = UIApplication.shared.delegate as! AppDelegate
@zdan. Good answer. I'd improve it like this...
I think that the closest you can come to a true return value in PowerShell is to use a local variable to pass the value and never to use return
as it may be 'corrupted' by any manner of output situations
function CheckRestart([REF]$retval)
{
# Some logic
$retval.Value = $true
}
[bool]$restart = $false
CheckRestart( [REF]$restart)
if ( $restart )
{
Restart-Computer -Force
}
The $restart
variable is used either side of the call to the function CheckRestart
making clear the scope of the variable. The return value can by convention be either the first or last parameter declared. I prefer last.
You have a typo in your xml; it should be:
android:textColor="@color/text_color"
that's "@color" without the 's'.
Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?
As so:
Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False
For Each element In sArray
XLSMToXLSX(element)
Next element
Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub
Sub XLSMToXLSX(ByVal file As String)
Do While WorkFile <> ""
If Right(WorkFile, 4) <> "xlsx" Then
Workbooks.Open Filename:=myPath & WorkFile
Application.DisplayAlerts = False
Application.EnableEvents = False
ActiveWorkbook.SaveAs Filename:= _
modifiedFileName, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False, _
ConflictResolution:=xlLocalSessionChanges
Application.DisplayAlerts = True
Application.EnableEvents = True
ActiveWorkbook.Close
End If
WorkFile = Dir()
Loop
End Sub
a = (b = 'string is truthy'); // b gets string; a gets b, which is a primitive (copy)
a = (b = { c: 'yes' }); // they point to the same object; a === b (not a copy)
(a && b)
is logically (a ? b : a)
and behaves like multiplication (eg. !!a * !!b
)
(a || b)
is logically (a ? a : b)
and behaves like addition (eg. !!a + !!b
)
(a = 0, b)
is short for not caring if a
is truthy, implicitly return b
a = (b = 0) && "nope, but a is 0 and b is 0"; // b is falsey + order of operations
a = (b = "b is this string") && "a gets this string"; // b is truthy + order of ops
JavaScript Operator Precedence (Order of Operations)
Note that the comma operator is actually the least privileged operator, but parenthesis are the most privileged, and they go hand-in-hand when constructing one-line expressions.
Eventually, you may need 'thunks' rather than hardcoded values, and to me, a thunk is both the function and the resultant value (the same 'thing').
const windowInnerHeight = () => 0.8 * window.innerHeight; // a thunk
windowInnerHeight(); // a thunk
The W3C doc doesn't use concepts like wrong and sin, but it does use those like provide the means, may be appropriate and discouraged.
Actually, in the second paragraph of section 4, the 4.01 spec itemizes its words as follows
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC2119]. However, for readability, these words do not appear in all uppercase letters in this specification.
With that in mind, I believe the definitive statement is in 7.5.3 Block-level and inline elements, where it says
Generally, inline elements may contain only data and other inline elements.
The condition "generally" appears to introduce enough ambiguity to say that HTML 4.01 does allow inline elements to contain block elements.
Certainly, CSS2 has a display property value, inline-block, that appears to be suited to the purpose you describe. I'm not sure if it was ever widely supported, but it seems that someone anticipated the need for that kind of behavior.
The DTD appear to be less forgiving here, but the text of the DTD defers to the spec:
The HTML 4.01 specification includes additional syntactic constraints that cannot be expressed within the DTDs.
In another comment, you suggest that you want to make a block active by wrapping it in an anchor. I don't believe HTML prohibits that, and CSS clearly allows it. So to answer the title question about whether it is ever correct, I say yes. By the standards, it is sometimes correct.
here is an example for right click context menu in javascript: Right Click Context Menu
Used raw javasScript Code for context menu functionality. Can you please check this, hope this will help you.
Live Code:
(function() {_x000D_
_x000D_
"use strict";_x000D_
_x000D_
_x000D_
/*********************************************** Context Menu Function Only ********************************/_x000D_
function clickInsideElement( e, className ) {_x000D_
var el = e.srcElement || e.target;_x000D_
if ( el.classList.contains(className) ) {_x000D_
return el;_x000D_
} else {_x000D_
while ( el = el.parentNode ) {_x000D_
if ( el.classList && el.classList.contains(className) ) {_x000D_
return el;_x000D_
}_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
function getPosition(e) {_x000D_
var posx = 0, posy = 0;_x000D_
if (!e) var e = window.event;_x000D_
if (e.pageX || e.pageY) {_x000D_
posx = e.pageX;_x000D_
posy = e.pageY;_x000D_
} else if (e.clientX || e.clientY) {_x000D_
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;_x000D_
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;_x000D_
}_x000D_
return {_x000D_
x: posx,_x000D_
y: posy_x000D_
}_x000D_
}_x000D_
_x000D_
// Your Menu Class Name_x000D_
var taskItemClassName = "thumb";_x000D_
var contextMenuClassName = "context-menu",contextMenuItemClassName = "context-menu__item",contextMenuLinkClassName = "context-menu__link", contextMenuActive = "context-menu--active";_x000D_
var taskItemInContext, clickCoords, clickCoordsX, clickCoordsY, menu = document.querySelector("#context-menu"), menuItems = menu.querySelectorAll(".context-menu__item");_x000D_
var menuState = 0, menuWidth, menuHeight, menuPosition, menuPositionX, menuPositionY, windowWidth, windowHeight;_x000D_
_x000D_
function initMenuFunction() {_x000D_
contextListener();_x000D_
clickListener();_x000D_
keyupListener();_x000D_
resizeListener();_x000D_
}_x000D_
_x000D_
/**_x000D_
* Listens for contextmenu events._x000D_
*/_x000D_
function contextListener() {_x000D_
document.addEventListener( "contextmenu", function(e) {_x000D_
taskItemInContext = clickInsideElement( e, taskItemClassName );_x000D_
_x000D_
if ( taskItemInContext ) {_x000D_
e.preventDefault();_x000D_
toggleMenuOn();_x000D_
positionMenu(e);_x000D_
} else {_x000D_
taskItemInContext = null;_x000D_
toggleMenuOff();_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
/**_x000D_
* Listens for click events._x000D_
*/_x000D_
function clickListener() {_x000D_
document.addEventListener( "click", function(e) {_x000D_
var clickeElIsLink = clickInsideElement( e, contextMenuLinkClassName );_x000D_
_x000D_
if ( clickeElIsLink ) {_x000D_
e.preventDefault();_x000D_
menuItemListener( clickeElIsLink );_x000D_
} else {_x000D_
var button = e.which || e.button;_x000D_
if ( button === 1 ) {_x000D_
toggleMenuOff();_x000D_
}_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
/**_x000D_
* Listens for keyup events._x000D_
*/_x000D_
function keyupListener() {_x000D_
window.onkeyup = function(e) {_x000D_
if ( e.keyCode === 27 ) {_x000D_
toggleMenuOff();_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Window resize event listener_x000D_
*/_x000D_
function resizeListener() {_x000D_
window.onresize = function(e) {_x000D_
toggleMenuOff();_x000D_
};_x000D_
}_x000D_
_x000D_
/**_x000D_
* Turns the custom context menu on._x000D_
*/_x000D_
function toggleMenuOn() {_x000D_
if ( menuState !== 1 ) {_x000D_
menuState = 1;_x000D_
menu.classList.add( contextMenuActive );_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Turns the custom context menu off._x000D_
*/_x000D_
function toggleMenuOff() {_x000D_
if ( menuState !== 0 ) {_x000D_
menuState = 0;_x000D_
menu.classList.remove( contextMenuActive );_x000D_
}_x000D_
}_x000D_
_x000D_
function positionMenu(e) {_x000D_
clickCoords = getPosition(e);_x000D_
clickCoordsX = clickCoords.x;_x000D_
clickCoordsY = clickCoords.y;_x000D_
menuWidth = menu.offsetWidth + 4;_x000D_
menuHeight = menu.offsetHeight + 4;_x000D_
_x000D_
windowWidth = window.innerWidth;_x000D_
windowHeight = window.innerHeight;_x000D_
_x000D_
if ( (windowWidth - clickCoordsX) < menuWidth ) {_x000D_
menu.style.left = (windowWidth - menuWidth)-0 + "px";_x000D_
} else {_x000D_
menu.style.left = clickCoordsX-0 + "px";_x000D_
}_x000D_
_x000D_
// menu.style.top = clickCoordsY + "px";_x000D_
_x000D_
if ( Math.abs(windowHeight - clickCoordsY) < menuHeight ) {_x000D_
menu.style.top = (windowHeight - menuHeight)-0 + "px";_x000D_
} else {_x000D_
menu.style.top = clickCoordsY-0 + "px";_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
function menuItemListener( link ) {_x000D_
var menuSelectedPhotoId = taskItemInContext.getAttribute("data-id");_x000D_
console.log('Your Selected Photo: '+menuSelectedPhotoId)_x000D_
var moveToAlbumSelectedId = link.getAttribute("data-action");_x000D_
if(moveToAlbumSelectedId == 'remove'){_x000D_
console.log('You Clicked the remove button')_x000D_
}else if(moveToAlbumSelectedId && moveToAlbumSelectedId.length > 7){_x000D_
console.log('Clicked Album Name: '+moveToAlbumSelectedId);_x000D_
}_x000D_
toggleMenuOff();_x000D_
}_x000D_
initMenuFunction();_x000D_
_x000D_
})();
_x000D_
/* For Body Padding and content */_x000D_
body { padding-top: 70px; }_x000D_
li a { text-decoration: none !important; }_x000D_
_x000D_
/* Thumbnail only */_x000D_
.thumb {_x000D_
margin-bottom: 30px;_x000D_
}_x000D_
.thumb:hover a, .thumb:active a, .thumb:focus a {_x000D_
border: 1px solid purple;_x000D_
}_x000D_
_x000D_
/************** For Context menu ***********/_x000D_
/* context menu */_x000D_
.context-menu { display: none; position: absolute; z-index: 9999; padding: 12px 0; width: 200px; background-color: #fff; border: solid 1px #dfdfdf; box-shadow: 1px 1px 2px #cfcfcf; }_x000D_
.context-menu--active { display: block; }_x000D_
_x000D_
.context-menu__items { list-style: none; margin: 0; padding: 0; }_x000D_
.context-menu__item { display: block; margin-bottom: 4px; }_x000D_
.context-menu__item:last-child { margin-bottom: 0; }_x000D_
.context-menu__link { display: block; padding: 4px 12px; color: #0066aa; text-decoration: none; }_x000D_
.context-menu__link:hover { color: #fff; background-color: #0066aa; }_x000D_
.context-menu__items ul { position: absolute; white-space: nowrap; z-index: 1; left: -99999em;}_x000D_
.context-menu__items > li:hover > ul { left: auto; padding-top: 5px ; min-width: 100%; }_x000D_
.context-menu__items > li li ul { border-left:1px solid #fff;}_x000D_
.context-menu__items > li li:hover > ul { left: 100%; top: -1px; }_x000D_
.context-menu__item ul { background-color: #ffffff; padding: 7px 11px; list-style-type: none; text-decoration: none; margin-left: 40px; }_x000D_
.page-media .context-menu__items ul li { display: block; }_x000D_
/************** For Context menu ***********/
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
<!-- Page Content -->_x000D_
<div class="container">_x000D_
_x000D_
<div class="row">_x000D_
_x000D_
<div class="col-lg-12">_x000D_
<h1 class="page-header">Thumbnail Gallery <small>(Right click to see the context menu)</small></h1>_x000D_
</div>_x000D_
_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
_x000D_
</div>_x000D_
<!-- /.container -->_x000D_
_x000D_
_x000D_
<!-- / The Context Menu -->_x000D_
<nav id="context-menu" class="context-menu">_x000D_
<ul class="context-menu__items">_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Delete This Photo"><i class="fa fa-empire"></i> Delete This Photo</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Photo Option 2"><i class="fa fa-envira"></i> Photo Option 2</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Photo Option 3"><i class="fa fa-first-order"></i> Photo Option 3</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Photo Option 4"><i class="fa fa-gitlab"></i> Photo Option 4</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Photo Option 5"><i class="fa fa-ioxhost"></i> Photo Option 5</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link"><i class="fa fa-arrow-right"></i> Add Photo to</a>_x000D_
<ul>_x000D_
<li><a href="#!" class="context-menu__link" data-action="album-one"><i class="fa fa-camera-retro"></i> Album One</a></li>_x000D_
<li><a href="#!" class="context-menu__link" data-action="album-two"><i class="fa fa-camera-retro"></i> Album Two</a></li>_x000D_
<li><a href="#!" class="context-menu__link" data-action="album-three"><i class="fa fa-camera-retro"></i> Album Three</a></li>_x000D_
<li><a href="#!" class="context-menu__link" data-action="album-four"><i class="fa fa-camera-retro"></i> Album Four</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>_x000D_
_x000D_
<!-- End # Context Menu -->_x000D_
_x000D_
_x000D_
</body>
_x000D_
You need to set the text after the replace call:
$('.element span').each(function() {_x000D_
console.log($(this).text());_x000D_
var text = $(this).text().replace('N/A, ', '');_x000D_
$(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
<span>N/A, Category</span>_x000D_
</div>
_x000D_
Here's another cool way you can do it (hat tip @Felix King):
$(".element span").text(function(index, text) {
return text.replace("N/A, ", "");
});
If I understand you right, you can do this:
<img src="image.png" style="background-color:red;" />
In fact, you can even apply a whole background-image
to the image, resulting in two "layers" without the need for multi-background support in the browser ;)
This is my LDAP Java login test application supporting LDAP:// and LDAPS:// self-signed test certificate. Code is taken from few SO posts, simplified implementation and removed legacy sun.java.* imports.
Usage
I have run this in Windows7 and Linux machines against WinAD directory service. Application prints username and member groups.
$ java -cp classes test.LoginLDAP url=ldap://1.2.3.4:389 [email protected] password=mypwd
$ java -cp classes test.LoginLDAP url=ldaps://1.2.3.4:636 [email protected] password=mypwd
Test application supports temporary self-signed test certificates for ldaps:// protocol, this DummySSLFactory accepts any server cert so man-in-the-middle is possible. Real life installation should import server certificate to a local JKS keystore file and not using dummy factory.
Application uses enduser's username+password for initial context and ldap queries, it works for WinAD but don't know if can be used for all ldap server implementations. You could create context with internal username+pwd then run queries to see if given enduser is found.
LoginLDAP.java
package test;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
public class LoginLDAP {
public static void main(String[] args) throws Exception {
Map<String,String> params = createParams(args);
String url = params.get("url"); // ldap://1.2.3.4:389 or ldaps://1.2.3.4:636
String principalName = params.get("username"); // [email protected]
String domainName = params.get("domain"); // mydomain.com or empty
if (domainName==null || "".equals(domainName)) {
int delim = principalName.indexOf('@');
domainName = principalName.substring(delim+1);
}
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, url);
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS, params.get("password")); // secretpwd
if (url.toUpperCase().startsWith("LDAPS://")) {
props.put(Context.SECURITY_PROTOCOL, "ssl");
props.put(Context.SECURITY_AUTHENTICATION, "simple");
props.put("java.naming.ldap.factory.socket", "test.DummySSLSocketFactory");
}
InitialDirContext context = new InitialDirContext(props);
try {
SearchControls ctrls = new SearchControls();
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", ctrls);
if(!results.hasMore())
throw new AuthenticationException("Principal name not found");
SearchResult result = results.next();
System.out.println("distinguisedName: " + result.getNameInNamespace() ); // CN=Firstname Lastname,OU=Mycity,DC=mydomain,DC=com
Attribute memberOf = result.getAttributes().get("memberOf");
if(memberOf!=null) {
for(int idx=0; idx<memberOf.size(); idx++) {
System.out.println("memberOf: " + memberOf.get(idx).toString() ); // CN=Mygroup,CN=Users,DC=mydomain,DC=com
//Attribute att = context.getAttributes(memberOf.get(idx).toString(), new String[]{"CN"}).get("CN");
//System.out.println( att.get().toString() ); // CN part of groupname
}
}
} finally {
try { context.close(); } catch(Exception ex) { }
}
}
/**
* Create "DC=sub,DC=mydomain,DC=com" string
* @param domainName sub.mydomain.com
* @return
*/
private static String toDC(String domainName) {
StringBuilder buf = new StringBuilder();
for (String token : domainName.split("\\.")) {
if(token.length()==0) continue;
if(buf.length()>0) buf.append(",");
buf.append("DC=").append(token);
}
return buf.toString();
}
private static Map<String,String> createParams(String[] args) {
Map<String,String> params = new HashMap<String,String>();
for(String str : args) {
int delim = str.indexOf('=');
if (delim>0) params.put(str.substring(0, delim).trim(), str.substring(delim+1).trim());
else if (delim==0) params.put("", str.substring(1).trim());
else params.put(str, null);
}
return params;
}
}
And SSL helper class.
package test;
import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.*;
import javax.net.ssl.*;
public class DummySSLSocketFactory extends SSLSocketFactory {
private SSLSocketFactory socketFactory;
public DummySSLSocketFactory() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{ new DummyTrustManager()}, new SecureRandom());
socketFactory = ctx.getSocketFactory();
} catch ( Exception ex ){ throw new IllegalArgumentException(ex); }
}
public static SocketFactory getDefault() { return new DummySSLSocketFactory(); }
@Override public String[] getDefaultCipherSuites() { return socketFactory.getDefaultCipherSuites(); }
@Override public String[] getSupportedCipherSuites() { return socketFactory.getSupportedCipherSuites(); }
@Override public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException {
return socketFactory.createSocket(socket, string, i, bln);
}
@Override public Socket createSocket(String string, int i) throws IOException, UnknownHostException {
return socketFactory.createSocket(string, i);
}
@Override public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException, UnknownHostException {
return socketFactory.createSocket(string, i, ia, i1);
}
@Override public Socket createSocket(InetAddress ia, int i) throws IOException {
return socketFactory.createSocket(ia, i);
}
@Override public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException {
return socketFactory.createSocket(ia, i, ia1, i1);
}
}
class DummyTrustManager implements X509TrustManager {
@Override public void checkClientTrusted(X509Certificate[] xcs, String str) {
// do nothing
}
@Override public void checkServerTrusted(X509Certificate[] xcs, String str) {
/*System.out.println("checkServerTrusted for authType: " + str); // RSA
for(int idx=0; idx<xcs.length; idx++) {
X509Certificate cert = xcs[idx];
System.out.println("X500Principal: " + cert.getSubjectX500Principal().getName());
}*/
}
@Override public X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}
Ctrl + F11 and Ctrl + F12 both work.
You can use an inflater with TableRow:
for (int i = 0; i < months; i++) {
View view = getLayoutInflater ().inflate (R.layout.list_month_data, null, false);
TextView textView = view.findViewById (R.id.title);
textView.setText ("Text");
tableLayout.addView (view);
}
Layout:
<TableRow
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:paddingTop="15dp"
android:paddingRight="15dp"
android:paddingLeft="15dp"
android:paddingBottom="10dp"
>
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:gravity="center"
/>
</TableRow>
If they're actually managed assemblies, you can use ILMerge. For native DLLs, you'll have a bit more work to do.
See also: How can a C++ windows dll be merged into a C# application exe?
There is nothing called float:bottom
in CSS. The best way is using positioning in such cases:
position:absolute;
bottom:0;
The Test-Connection command seems to be a useful alternative, and it can either provide either a Win32_PingStatus object, or a boolean value.
Documentation: https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.management/test-connection
I have a function which returns a CLOB and I was seeing the above error when I'd forgotten to declare the return value as an output parameter. Initially I had:
protected SimpleJdbcCall buildJdbcCall(JdbcTemplate jdbcTemplate)
{
SimpleJdbcCall call = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(catalog)
.withFunctionName(functionName)
.withReturnValue()
.declareParameters(buildSqlParameters());
return call;
}
public SqlParameter[] buildSqlParameters() {
return new SqlParameter[]{
new SqlParameter("p_names", Types.VARCHAR),
new SqlParameter("p_format", Types.VARCHAR),
new SqlParameter("p_units", Types.VARCHAR),
new SqlParameter("p_datums", Types.VARCHAR),
new SqlParameter("p_start", Types.VARCHAR),
new SqlParameter("p_end", Types.VARCHAR),
new SqlParameter("p_timezone", Types.VARCHAR),
new SqlParameter("p_office_id", Types.VARCHAR),
};
}
The buildSqlParameters method should have included the SqlOutParameter:
public SqlParameter[] buildSqlParameters() {
return new SqlParameter[]{
new SqlParameter("p_names", Types.VARCHAR),
new SqlParameter("p_format", Types.VARCHAR),
new SqlParameter("p_units", Types.VARCHAR),
new SqlParameter("p_datums", Types.VARCHAR),
new SqlParameter("p_start", Types.VARCHAR),
new SqlParameter("p_end", Types.VARCHAR),
new SqlParameter("p_timezone", Types.VARCHAR),
new SqlParameter("p_office_id", Types.VARCHAR),
new SqlOutParameter("l_clob", Types.CLOB) // <-- This was missing!
};
}
I can fix this by adding below code in my JSP file. Now both model and UI values are same.
<div ng-show="false">
{{dt = (dt | date:'dd-MMMM-yyyy') }}
</div>
One possible way is using a deploy token (https://docs.gitlab.com/ee/user/project/deploy_tokens). After creating the token, use:
git clone https://<username>:<deploy_token>@gitlab.example.com/tanuki/awesome_project.git
as mentioned in the link above.
you can still use
String Item = getIntent().getExtras().getString("name");
in the fragment
, you just need call getActivity()
first:
String Item = getActivity().getIntent().getExtras().getString("name");
This saves you having to write some code.
Small improvement to the code from ryyst (who got the most votes) is to not use dynamically allocated decoding table but rather static const precomputed table. This eliminates the use of pointer and initialization of the table, and also avoids memory leakage if one forgets to clean up the decoding table with base64_cleanup() (by the way, in base64_cleanup(), after calling free(decoding_table), one should have decoding_table=NULL, otherwise accidentally calling base64_decode after base64_cleanup() will crash or cause undetermined behavior). Another solution could be to use std::unique_ptr...but I'm satisfied with just having const char[256] on the stack and avoid using pointers alltogether - the code looks cleaner and shorter this way.
The decoding table is computed as follows:
const char encoding_table[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/' };
unsigned char decoding_table[256];
for (int i = 0; i < 256; i++)
decoding_table[i] = '\0';
for (int i = 0; i < 64; i++)
decoding_table[(unsigned char)encoding_table[i]] = i;
for (int i = 0; i < 256; i++)
cout << "0x" << (int(decoding_table[i]) < 16 ? "0" : "") << hex << int(decoding_table[i]) << (i != 255 ? "," : "") << ((i+1) % 16 == 0 ? '\n' : '\0');
cin.ignore();
and the modified code I am using is:
static const char encoding_table[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/' };
static const unsigned char decoding_table[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x3f,
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
char* base64_encode(const unsigned char *data, size_t input_length, size_t &output_length) {
const int mod_table[] = { 0, 2, 1 };
output_length = 4 * ((input_length + 2) / 3);
char *encoded_data = (char*)malloc(output_length);
if (encoded_data == nullptr)
return nullptr;
for (int i = 0, j = 0; i < input_length;) {
uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
}
for (int i = 0; i < mod_table[input_length % 3]; i++)
encoded_data[output_length - 1 - i] = '=';
return encoded_data;
};
unsigned char* base64_decode(const char *data, size_t input_length, size_t &output_length) {
if (input_length % 4 != 0)
return nullptr;
output_length = input_length / 4 * 3;
if (data[input_length - 1] == '=') (output_length)--;
if (data[input_length - 2] == '=') (output_length)--;
unsigned char* decoded_data = (unsigned char*)malloc(output_length);
if (decoded_data == nullptr)
return nullptr;
for (int i = 0, j = 0; i < input_length;) {
uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t triple = (sextet_a << 3 * 6)
+ (sextet_b << 2 * 6)
+ (sextet_c << 1 * 6)
+ (sextet_d << 0 * 6);
if (j < output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
if (j < output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
if (j < output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
}
return decoded_data;
};
To get better results and robustness against differents types of matrices, you can do this in addition to the first answer, that copy the data :
cv::Mat source = getYourSource();
// Setup a rectangle to define your region of interest
cv::Rect myROI(10, 10, 100, 100);
// Crop the full image to that image contained by the rectangle myROI
// Note that this doesn't copy the data
cv::Mat croppedRef(source, myROI);
cv::Mat cropped;
// Copy the data into new matrix
croppedRef.copyTo(cropped);
I think these kinds of problems are solved if we think about real life.
Bad Practice:
Example 1:
Darling everything is FINE/OK (HTTP CODE 200) - (Success):
{
...but I don't want us to be together anymore!!!... (Error)
// Then everything isn't OK???
}
Example 2:
You are the best employee (HTTP CODE 200) - (Success):
{
...But we cannot continue your contract!!!... (Error)
// Then everything isn't OK???
}
Good Practices:
Darling I don't feel good (HTTP CODE 400) - (Error):
{
...I no longer feel anything for you, I think the best thing is to separate... (Error)
// In this case, you are alerting me from the beginning that something is wrong ...
}
This is only my personal opinion, each one can implement it as it is most comfortable or needs.
Note: The idea for this explanation was drawn from a great friend @diosney
Just put the condition into the lambda itself, e.g.
animalMap.entrySet().stream()
.forEach(
pair -> {
if (pair.getValue() != null) {
myMap.put(pair.getKey(), pair.getValue());
} else {
myList.add(pair.getKey());
}
}
);
Of course, this assumes that both collections (myMap
and myList
) are declared and initialized prior to the above piece of code.
Update: using Map.forEach
makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:
animalMap.forEach(
(key, value) -> {
if (value != null) {
myMap.put(key, value);
} else {
myList.add(key);
}
}
);
The playbook script task will generate stdout
just like the non-playbook command, it just needs to be saved to a variable using register
. Once we've got that, the debug module can print to the playbook output stream.
tasks:
- name: Hello yourself
script: test.sh
register: hello
- name: Debug hello
debug: var=hello
- name: Debug hello.stdout as part of a string
debug: "msg=The script's stdout was `{{ hello.stdout }}`."
Output should look something like this:
TASK: [Hello yourself] ********************************************************
changed: [MyTestHost]
TASK: [Debug hello] ***********************************************************
ok: [MyTestHost] => {
"hello": {
"changed": true,
"invocation": {
"module_args": "test.sh",
"module_name": "script"
},
"rc": 0,
"stderr": "",
"stdout": "Hello World\r\n",
"stdout_lines": [
"Hello World"
]
}
}
TASK: [Debug hello.stdout as part of a string] ********************************
ok: [MyTestHost] => {
"msg": "The script's stdout was `Hello World\r\n`."
}
in C#:
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1)
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1)
Recommended solution is to install and trust a self-signed certificate (root). Assuming you created your own CA and the hierarchy of the certificated is correct you don't need to change the server trust evaluation. This is recommended because it doesn't require any changes in the code.
If it is not possible then you need to change server trust evaluation.
More info in this document: Technical Q&A QA1948 HTTPS and Test Servers
TL;DR: Scan down to image, and then check out working project here.
Updating my answer for a simpler solution that I found..
In my case, I wanted to fix the width, and have variable height cells. I wanted a drop in, reusable solution that handled rotation and didn't require a lot of intervention.
What I arrived at, was override (just) systemLayoutFitting(...)
in the collection cell (in this case a base class for me), and first defeat UICollectionView's effort to set the wrong dimension on contentView
by adding a constraint for the known dimension, in this case, the width.
class EstimatedWidthCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
contentView.translatesAutoresizingMaskIntoConstraints = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
contentView.translatesAutoresizingMaskIntoConstraints = false
}
override func systemLayoutSizeFitting(
_ targetSize: CGSize, withHorizontalFittingPriority
horizontalFittingPriority: UILayoutPriority,
verticalFittingPriority: UILayoutPriority) -> CGSize {
width.constant = targetSize.width
and then return the final size for the cell - used for (and this feels like a bug) the dimension of the cell itself, but not contentView
- which is otherwise constrained to a conflicting size (hence the constraint above). To calculate the correct cell size, I use a lower priority for the dimension that I wanted to float, and I get back the height required to fit the content within the width to which I want to fix:
let size = contentView.systemLayoutSizeFitting(
CGSize(width: targetSize.width, height: 1),
withHorizontalFittingPriority: .required,
verticalFittingPriority: verticalFittingPriority)
print("\(#function) \(#line) \(targetSize) -> \(size)")
return size
}
lazy var width: NSLayoutConstraint = {
return contentView.widthAnchor
.constraint(equalToConstant: bounds.size.width)
.isActive(true)
}()
}
But where does this width come from? It is configured via the estimatedItemSize
on the collection view's flow layout:
lazy var collectionView: UICollectionView = {
let view = UICollectionView(frame: CGRect(), collectionViewLayout: layout)
view.backgroundColor = .cyan
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var layout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
let width = view.bounds.size.width // should adjust for inset
layout.estimatedItemSize = CGSize(width: width, height: 10)
layout.scrollDirection = .vertical
return layout
}()
Finally, to handle rotation, I implement trailCollectionDidChange
to invalidate the layout:
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
layout.estimatedItemSize = CGSize(width: view.bounds.size.width, height: 10)
layout.invalidateLayout()
super.traitCollectionDidChange(previousTraitCollection)
}
The final result looks like this:
And I have published a working sample here.
You have to catch the SIGINT signal (we are talking POSIX right?)
See @Gab Royer´s answer for sigaction.
Example:
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
void my_handler(sig_t s){
printf("Caught signal %d\n",s);
exit(1);
}
int main(int argc,char** argv)
{
signal (SIGINT,my_handler);
while(1);
return 0;
}
This isn't necessarily exhaustive.
options = {...optionsDefault, ...options};
If authoring code for execution in environments without native support, you may be able to just compile this syntax (as opposed to using a polyfill). (With Babel, for example.)
Less verbose.
When this answer was originally written, this was a proposal, not standardized. When using proposals consider what you'd do if you write code with it now and it doesn't get standardized or changes as it moves toward standardization. This has since been standardized in ES2018.
Literal, not dynamic.
Object.assign()
options = Object.assign({}, optionsDefault, options);
Standardized.
Dynamic. Example:
var sources = [{a: "A"}, {b: "B"}, {c: "C"}];
options = Object.assign.apply(Object, [{}].concat(sources));
// or
options = Object.assign({}, ...sources);
This is the commit that made me wonder.
That's not directly related to what you're asking. That code wasn't using Object.assign()
, it was using user code (object-assign
) that does the same thing. They appear to be compiling that code with Babel (and bundling it with Webpack), which is what I was talking about: the syntax you can just compile. They apparently preferred that to having to include object-assign
as a dependency that would go into their build.
Because of the thousand separator, the data will have been read as 'non-numeric'. So you need to convert it:
we <- gsub(",", "", we) # remove comma
we <- as.numeric(we) # turn into numbers
and now you can do
hist(we)
and other numeric operations.
max-width
works for me.
aside {
flex: 0 1 200px;
max-width: 200px;
}
Variables of CSS pre-processors allows to avoid hard-coding.
aside {
$WIDTH: 200px;
flex: 0 1 $WIDTH;
max-width: $WIDTH;
}
overflow: hidden
also works, but I lately I try do not use it because it hides the elements as popups and dropdowns.
@echo off
set countfiles=10
:loop
set /a countfiles -= 1
echo hi
if %countfiles% GTR 0 goto loop
pause
on the first "set countfiles" the 10 you see is the amount it will loop the echo hi is the thing you want to loop
...i'm 5 years late
This XPath:
count(//Property[long = '11007'])
returns the same value as:
count(//Property/long[text() = '11007'])
...except that the first counts Property
nodes that match the criterion and the second counts long
child nodes that match the criterion.
As per your comment and reading your question a couple of times, I believe that you want to find uniqueness based on a combination of criteria. Therefore, in actuality, I think you are actually checking multiple conditions. The following would work as well:
count(//Property[@Name = 'Alive'][long = '11007'])
because it means the same thing as:
count(//Property[@Name = 'Alive' and long = '11007'])
Of course, you would substitute the values for parameters in your template. The above code only illustrates the point.
EDIT (after question edit)
You were quite right about the XML being horrible. In fact, this is a downright CodingHorror candidate! I had to keep recounting to keep track of the "Property" node I was on presently. I feel your pain!
Here you go:
count(/root/ac/Properties/Property[Properties/Property/Properties/Property/long = $parPropId])
Note that I have removed all the other checks (for ID and Value). They appear not to be required since you are able to arrive at the relevant node using the hierarchy in the XML. Also, you already mentioned that the check for uniqueness is based only on the contents of the long
element.
Update
I've written a cross-browser range and selection library called Rangy that incorporates an improved version of the code I posted below. You can use the selection save and restore module for this particular question, although I'd be tempted to use something like @Nico Burns's answer if you're not doing anything else with selections in your project and don't need the bulk of a library.
Previous answer
You can use IERange (http://code.google.com/p/ierange/) to convert IE's TextRange into something like a DOM Range and use it in conjunction with something like eyelidlessness's starting point. Personally I would only use the algorithms from IERange that do the Range <-> TextRange conversions rather than use the whole thing. And IE's selection object doesn't have the focusNode and anchorNode properties but you should be able to just use the Range/TextRange obtained from the selection instead.
I might put something together to do this, will post back here if and when I do.
EDIT:
I've created a demo of a script that does this. It works in everything I've tried it in so far except for a bug in Opera 9, which I haven't had time to look into yet. Browsers it works in are IE 5.5, 6 and 7, Chrome 2, Firefox 2, 3 and 3.5, and Safari 4, all on Windows.
http://www.timdown.co.uk/code/selections/
Note that selections may be made backwards in browsers so that the focus node is at the start of the selection and hitting the right or left cursor key will move the caret to a position relative to the start of the selection. I don't think it is possible to replicate this when restoring a selection, so the focus node is always at the end of the selection.
I will write this up fully at some point soon.
Everything that interacts with the UI must be called in the UI thread (unless it is a frozen object). To do that, you can use the dispatcher.
var disp = /* Get the UI dispatcher, each WPF object has a dispatcher which you can query*/
disp.BeginInvoke(DispatcherPriority.Normal,
(Action)(() => /*Do your UI Stuff here*/));
I use BeginInvoke here, usually a backgroundworker doesn't need to wait that the UI updates. If you want to wait, you can use Invoke
. But you should be careful not to call BeginInvoke to fast to often, this can get really nasty.
By the way, The BackgroundWorker class helps with this kind of taks. It allows Reporting changes, like a percentage and dispatches this automatically from the Background thread into the ui thread. For the most thread <> update ui tasks the BackgroundWorker is a great tool.
What you want is a timer:
// RxJS v6+
import { timer } from 'rxjs';
//emit [1, 2, 3] after 1 second.
const source = timer(1000).map(([1, 2, 3]);
//output: [1, 2, 3]
const subscribe = source.subscribe(val => console.log(val));
There are multiple nuget packages read in the following order:
NuGetDefaults.Config file
. You will find this in %ProgramFiles(x86)%\NuGet\Config
.%APPDATA%\NuGet\nuget.config
.nuget.config
beginning from the root of your drive up to the directory where nuget.exe is called.You can find more information here.
For %F In ("C:\From\*.*") Do If Not Exist "C:\To\%~nxF" Copy "%F" "C:\To\%~nxF"
If you have a full DB dump:
PGPASSWORD="your_pass" psql -h "your_host" -U "your_user" -d "your_database" -f backup.sql
If you have schemas kept separately, however, that won't work. Then you'll need to disable triggers for data insertion, akin to pg_restore --disable-triggers
. You can then use this:
cat database_data_only.gzip | gunzip | PGPASSWORD="your_pass" psql -h "your_host" -U root "your_database" -c 'SET session_replication_role = replica;' -f /dev/stdin
On a side note, it is a very unfortunate downside of postgres, I think. The default way of creating a dump in pg_dump
is incompatible with pg_restore
. With some additional keys, however, it is. WTF?
The first code line, Option Explicit
means (in simple terms) that all of your variables have to be explicitly declared by Dim
statements. They can be any type, including object, integer, string, or even a variant.
This line: Dim envFrmwrkPath As Range
is declaring the variable envFrmwrkPath
of type Range
. This means that you can only set it to a range.
This line: Set envFrmwrkPath = ActiveSheet.Range("D6").Value
is attempting to set the Range
type variable to a specific Value that is in cell D6
. This could be a integer or a string for example (depends on what you have in that cell) but it's not a range.
I'm assuming you want the value stored in a variable. Try something like this:
Dim MyVariableName As Integer
MyVariableName = ActiveSheet.Range("D6").Value
This assumes you have a number (like 5) in cell D6. Now your variable will have the value.
For simplicity sake of learning, you can remove or comment out the Option Explicit
line and VBA will try to determine the type of variables at run time.
Try this to get through this part of your code
Dim envFrmwrkPath As String
Dim ApplicationName As String
Dim TestIterationName As String
Take care not to include
#include <string.h>
but only
#include <string>
It took me 1 hour to find this in my code.
Hope this can help
I ran to a similar error running Excel in VBA, what I've learned is that when I pull data from MSSQL, and then using get_range
and .Value2
apply it's out of the range, any value that was of type uniqueidentifier
(GUID) resulted in this error.
Only when I cast the value to nvarcahr(max)
it worked.
Faced the problem of missing stdlib.h
and stdio.h
(and maybe more) after installing VS2017 Community on a new computer and migrating a solution from VS2013 to VS2017.
Used @Maxim Akristiniy's proposal, but still got error message regarding toolset compatibility. However VS itself suggested to do solution retarget by right-clicking on the solution in Solution Explorer, then selecting Retarget solution
from the menu and the updated Windows SDK Version
from the drop-down list.
Now my projects build w/o a problem.
Note that you may need to make the project your startup project for the retargeting to catch.
Years passed and nowadays you can do it natively
(new TextEncoder().encode('foo')).length
Note that it's not supported by IE (you may use a polyfill for that).
I'm just getting my feet wet with angular, but I found this great tutorial.
Here's a working plunk I put together with credit to Scott Allen and the above tutorial. Click search to display the sortable table.
For each column header you need to make it clickable - ng-click on a link will work. This will set the sortName of the column to sort.
<th>
<a href="#" ng-click="sortName='name'; sortReverse = !sortReverse">
<span ng-show="sortName == 'name' && sortReverse" class="glyphicon glyphicon-triangle-bottom"></span>
<span ng-show="sortName == 'name' && !sortReverse" class="glyphicon glyphicon-triangle-top"></span>
Name
</a>
</th>
Then, in the table body you can pipe in that sortName in the orderBy filter orderBy:sortName:sortReverse
<tr ng-repeat="repo in repos | orderBy:sortName:sortReverse | filter:searchRepos">
<td>{{repo.name}}</td>
<td class="tag tag-primary">{{repo.stargazers_count | number}}</td>
<td>{{repo.language}}</td>
</tr>
Got the error (in the function init) with the following code ;
"use strict" ;
var hdr ;
function init(){ // called on load
hdr = document.getElementById("hdr");
}
... while using the stock browser on a Samsung galaxy Fame ( crap phone which makes it a good tester ) - userAgent ; Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-S6810P Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
The same code works everywhere else I tried including the stock browser on an older HTC phone - userAgent ; Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; HTC_WildfireS_A510e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
The fix for this was to change
var hdr ;
to
var hdr = null ;
In short you have to do like this
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "https://maven.fabric.io/public" }
}
Detail:
You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:
apply plugin: 'java'
sourceCompatibility = 1.7
version = '1.0'
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
dependencies {
compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
testCompile group:'junit', name:'junit', version:'4.11'
}
Following @Shruthi Kamoji in a cleaner way, we can just use a filterable, its meant for that:
public abstract class GenericRecycleAdapter<E> extends RecyclerView.Adapter implements Filterable
{
protected List<E> list;
protected List<E> originalList;
protected Context context;
public GenericRecycleAdapter(Context context,
List<E> list)
{
this.originalList = list;
this.list = list;
this.context = context;
}
...
@Override
public Filter getFilter() {
return new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
list = (List<E>) results.values;
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<E> filteredResults = null;
if (constraint.length() == 0) {
filteredResults = originalList;
} else {
filteredResults = getFilteredResults(constraint.toString().toLowerCase());
}
FilterResults results = new FilterResults();
results.values = filteredResults;
return results;
}
};
}
protected List<E> getFilteredResults(String constraint) {
List<E> results = new ArrayList<>();
for (E item : originalList) {
if (item.getName().toLowerCase().contains(constraint)) {
results.add(item);
}
}
return results;
}
}
The E here is a Generic Type, you can extend it using your class:
public class customerAdapter extends GenericRecycleAdapter<CustomerModel>
Or just change the E to the type you want (<CustomerModel>
for example)
Then from searchView (the widget you can put on menu.xml):
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String text) {
return false;
}
@Override
public boolean onQueryTextChange(String text) {
yourAdapter.getFilter().filter(text);
return true;
}
});
Just create a new field to bypass this security thing:
var $oldPassword = $("#password");
var $newPassword = $("<input type='text' />")
.val($oldPassword.val())
.appendTo($oldPassword.parent());
$oldPassword.remove();
$newPassword.attr('id','password');
input[type="text"]{
@include transition(all 0.30s ease-in-out);
outline: none;
padding: 3px 0px 3px 3px;
margin: 5px 1px 3px 0px;
border: 1px solid #DDDDDD;
}
input[type="text"]:focus{
@include box-shadow(0 0 5px rgba(81, 203, 238, 1));
-webkit-box-shadow: 0px 0px 5px #007eff;
-moz-box-shadow: 0px 0px 5px #007eff;
box-shadow: 0px 0px 5px #007eff;
}
project link:
https://github.com/your_username/you_repo_name/settings
you will get a page like this, go to Collaborator and add collaborator
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/activity_register_header"
android:minHeight="50dp"
android:orientation="vertical"
android:visibility="gone" />
Try this piece of code..For me this code worked..
Workaround: Rename directory which is not 'working copy' Checkout/update/restore this directory again Move files from renamed directory to new Commit changes
Reason: You made some changes to some files under .svn directory, this breaks 'working copy'
An alternative ugly method:
String[] a ={"BLAH00001","DIK-11","DIK-2","MAN5"};
String[] k=Arrays.toString(a).split(", ",2)[1].split("]")[0].split(", ");
If you Want to run Batch Subscribe on a List using Mailchimp API . Then you can use the below function.
/**
* Mailchimp API- List Batch Subscribe added function
*
* @param array $data Passed you data as an array format.
* @param string $apikey your mailchimp api key.
*
* @return mixed
*/
function batchSubscribe(array $data, $apikey)
{
$auth = base64_encode('user:' . $apikey);
$json_postData = json_encode($data);
$ch = curl_init();
$dataCenter = substr($apikey, strpos($apikey, '-') + 1);
$curlopt_url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/batches/';
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic ' . $auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_postData);
$result = curl_exec($ch);
return $result;
}
Function Use And Data format for Batch Operations:
<?php
$apikey = 'Your MailChimp Api Key';
$list_id = 'Your list ID';
$servername = 'localhost';
$username = 'Youre DB username';
$password = 'Your DB password';
$dbname = 'Your DB Name';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
$sql = 'SELECT * FROM emails';// your SQL Query goes here
$result = $conn->query($sql);
$finalData = [];
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$individulData = array(
'apikey' => $apikey,
'email_address' => $row['email'],
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => 'eastwest',
'LNAME' => 'rehab',
)
);
$json_individulData = json_encode($individulData);
$finalData['operations'][] =
array(
"method" => "POST",
"path" => "/lists/$list_id/members/",
"body" => $json_individulData
);
}
}
$api_response = batchSubscribe($finalData, $apikey);
print_r($api_response);
$conn->close();
Also, You can found this code in my Github gist. GithubGist Link
Reference Documentation: Official
I am adding this answer in case someone else would like to store the host entry set in a txt file formatted like the normal host file. This looks for a TAB delimiter. This is based off of the answers from @Rashy and @that0n3guy. The differences can be noticed around the FOR command.
@echo off
TITLE Modifying your HOSTS file
ECHO.
:: BatchGotAdmin
:-------------------------------------
REM --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"="
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"
IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%
ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop
:REJECTED
ECHO Your HOSTS file was left unchanged.
ECHO Finished.
GOTO END
:ACCEPTED
setlocal enabledelayedexpansion
::Create your list of host domains
for /F "tokens=1,2 delims= " %%A in (%WINDIR%\System32\drivers\etc\storedhosts.txt) do (
SET _host=%%B
SET _ip=%%A
SET NEWLINE=^& echo.
ECHO Adding !_ip! !_host!
REM REM ::strip out this specific line and store in tmp file
type %WINDIR%\System32\drivers\etc\hosts | findstr /v !_host! > tmp.txt
REM REM ::re-add the line to it
ECHO %NEWLINE%^!_ip! !_host! >> tmp.txt
REM ::overwrite host file
copy /b/v/y tmp.txt %WINDIR%\System32\drivers\etc\hosts
del tmp.txt
)
ipconfig /flushdns
ECHO.
ECHO.
ECHO Finished, you may close this window now.
GOTO END
:END
ECHO.
PAUSE
EXIT
Example "storedhosts.txt" (tab delimited)
127.0.0.1 mysite.com
168.1.64.2 yoursite.com
192.1.0.1 internalsite.com
You can delete the selected item with this:
$("#selectBox option:selected").remove();
This is useful if you have a list and not a dropdown.
Similar as they are, merge!
and store
treat existing hashes differently depending on keynames, and will therefore affect your preference. Other than that from a syntax standpoint, merge!
's key: "value"
syntax closely matches up against JavaScript and Python. I've always hated comma-separating key-value pairs, personally.
hash = {}
hash.merge!(key: "value")
hash.merge!(:key => "value")
puts hash
{:key=>"value"}
hash = {}
hash.store(:key, "value")
hash.store("key", "value")
puts hash
{:key=>"value", "key"=>"value"}
To get the shovel operator <<
working, I would advise using Mark Thomas's answer.
Use getattr
to get an attribute from a name in a string. In other words, get the instance as
instance = getattr(modul, class_name)()
if x
is a vector with raw scores then scale(x)
is a vector with standardized scores.
Or manually: (x-mean(x))/sd(x)
You could try implemeting something like this: http://www.codeproject.com/KB/cs/reporting__windowsforms.aspx
I tried some of your solutions. This one :
margin: 0px -100%;
padding: 0 100%;
is by far the best, since we don't need extra css for smaller screen. I made a codePen to show the results : I used a parent div with a background image, and a child divon div with inner content.
indeed, all of these datetime types can be difficult, and potentially problematic (must keep careful track of timezone information). here's what i have done, though i admit that i am concerned that at least part of it is "not by design". also, this can be made a bit more compact as needed. starting with a numpy.datetime64 dt_a:
dt_a
numpy.datetime64('2015-04-24T23:11:26.270000-0700')
dt_a1 = dt_a.tolist() # yields a datetime object in UTC, but without tzinfo
dt_a1
datetime.datetime(2015, 4, 25, 6, 11, 26, 270000)
# now, make your "aware" datetime:
dt_a2=datetime.datetime(*list(dt_a1.timetuple()[:6]) + [dt_a1.microsecond], tzinfo=pytz.timezone('UTC'))
... and of course, that can be compressed into one line as needed.
You cannot include style directives in GFM.
The most complete documentation/example is "Markdown Cheatsheet", and it illustrates that this element <style>
is missing.
If you manage to include your text in one of the GFM elements, then you can play with a github.css stylesheet in order to colors that way, meaning to color using inline CSS style directives, referring to said css stylesheet.
The solution is actually described here: http://www.anujgakhar.com/2013/06/15/duplicates-in-a-repeater-are-not-allowed-in-angularjs/
AngularJS does not allow duplicates in a ng-repeat directive. This means if you are trying to do the following, you will get an error.
// This code throws the error "Duplicates in a repeater are not allowed.
// Repeater: row in [1,1,1] key: number:1"
<div ng-repeat="row in [1,1,1]">
However, changing the above code slightly to define an index to determine uniqueness as below will get it working again.
// This will work
<div ng-repeat="row in [1,1,1] track by $index">
Official docs are here: https://docs.angularjs.org/error/ngRepeat/dupes
Use uintptr_t
as your integer type.
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
Here is a Swift 3 version:
private func getHtmlLabel(text: String) -> UILabel {
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.attributedString = stringFromHtml(string: text)
return label
}
private func stringFromHtml(string: String) -> NSAttributedString? {
do {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
if let d = data {
let str = try NSAttributedString(data: d,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
return str
}
} catch {
}
return nil
}
I found issues with some of the other answers here and it took me a bit to get this right. I set the line break mode and number of lines so that the label sized appropriately when the HTML spanned multiple lines.
Here is my 2 cents. Create an empty invisible div. Fill it with the input content and return the width to the input field. Match text styles between each box.
$(".answers_number").keyup(function(){_x000D_
$( "#number_box" ).html( $( this ).val() );_x000D_
$( this ).animate({_x000D_
width: $( "#number_box" ).width()+20_x000D_
}, 300, function() {_x000D_
});_x000D_
});
_x000D_
#number_box {_x000D_
position: absolute;_x000D_
visibility: hidden;_x000D_
height: auto;_x000D_
width: auto;_x000D_
white-space: nowrap;_x000D_
padding:0 4px;_x000D_
/*Your font styles to match input*/_x000D_
font-family:Arial;_x000D_
font-size: 30px; _x000D_
}_x000D_
_x000D_
.answers_number {_x000D_
font-size: 30px; _x000D_
font-family:Arial;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="number" class="answers_number" />_x000D_
<div id="number_box">_x000D_
</div>
_x000D_
I found it in /usr/local/nginx/logs/*
.
<style type="text/css">
span {
position:absolute;
width: 50px;
}
</style>
You can do this method for assigning width for inline elements
On Linux, Unix, Git Bash, or Cygwin, try:
rm -f .git/index.lock
On Windows Command Prompt, try:
del .git\index.lock
For Windows:
From a PowerShell console opened as administrator, try
rm -Force ./.git/index.lock
If that does not work, you must kill all git.exe processes
taskkill /F /IM git.exe
SUCCESS: The process "git.exe" with PID 20448 has been terminated.
SUCCESS: The process "git.exe" with PID 11312 has been terminated.
SUCCESS: The process "git.exe" with PID 23868 has been terminated.
SUCCESS: The process "git.exe" with PID 27496 has been terminated.
SUCCESS: The process "git.exe" with PID 33480 has been terminated.
SUCCESS: The process "git.exe" with PID 28036 has been terminated. \
rm -Force ./.git/index.lock
to modify more css property values, you may use css object. such as:
hilight_css = {"border-bottom-color":"red",
"background-color":"#000"};
$(".msg").css(hilight_css);
but if the modification code is bloated. you should consider the approach March suggested. do it this way:
first, in your css file:
.hilight { border-bottom-color:red; background-color:#000; }
.msg { /* something to make it notifiable */ }
second, in your js code:
$(".msg").addClass("hilight");
// to bring message block to normal
$(".hilight").removeClass("hilight");
if ie 6 is not an issue, you can chain these classes to have more specific selectors.
In general, if you are using white-space: nowrap;
it is probably because you know which columns are going to contain content which wraps (or stretches the cell). For those columns, I generally wrap the cell's contents in a span
with a specific class
attribute and apply a specific width
.
Example:
HTML:
<td><span class="description">My really long description</span></td>
CSS:
span.description {
display: inline-block;
overflow: hidden;
white-space: nowrap;
width: 150px;
}
config
is another option:
widget1.config(bg='black')
widget2.config(bg='#000000')
or:
widget1.config(background='black')
widget2.config(background='#000000')
try this:
key=key.replace(/ /g,"_");
that'll do a global find/replace
Well I did a bit of searching around the internet for you and I found this handy link.
Easiest way to find duplicate values in a JavaScript array
You can adapt the sample code that is provided in the above link, courtesy of "swilliams" to your solution.
Just one more example how the character could be flipped. Add vendor prefixes if you need ones but for now all modern browsers support unprefixed transform property. The only exception is Opera if Opera Mini mode is enabled (~3% world users).
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Text rotation</title>_x000D_
<style type="text/css" media="screen">_x000D_
.scissors {_x000D_
display: inline-block;_x000D_
font-size: 50px;_x000D_
color: red;_x000D_
}_x000D_
.original {_x000D_
color: initial;_x000D_
}_x000D_
.flipped {_x000D_
transform: rotateZ(180deg);_x000D_
}_x000D_
.upward {_x000D_
transform: rotateZ(-90deg);_x000D_
}_x000D_
.downward {_x000D_
transform: rotateZ(90deg);_x000D_
}_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<ul>_x000D_
<li>Original: <span class="scissors original">✂</span></li>_x000D_
<li>Flipped: <span class="scissors flipped">✂</span></li>_x000D_
<li>Upward: <span class="scissors upward">✂</span></li>_x000D_
<li>Downward: <span class="scissors downward">✂</span></li>_x000D_
</ul>_x000D_
</body>_x000D_
</html>
_x000D_
Use below command in Debian based container:
apt-get install vim-tiny
Complete instruction for using in Dockerfile:
RUN apt-get update && apt-get install --no-install-recommends -y \
vim-tiny \
&& apt-get clean && rm -rf /var/lib/apt/lists/*
It doesn't install unnecessary packages and removes unnecessary downloaded files, so your docker image size won't increase dramatically.
It's even easier if you consider that the Generic List in C# is indexed from 0 like an array. This means you can just use something like:
int index = 0; int i = accounts[index];
Seems to work
$(".selector").change(function() {
var $value = $(this).val();
var $title = $(this).children('option[value='+$value+']').html();
$('#bacon').val($title);
});
Just check with your firebug. And don't put css on hidden input.
(^(\d{2})|^(\d{4})|^(\d{5}))$
This expression takes the number of length 2,4 and 5. Valid Inputs are 12 1234 12345
It can easilly be done with ArgueJS:
function myFunction ()
{
arguments = __({myDate: Date, myString: String});
// do stuff
};
Why don't you use the BigInteger(String)
constructor ? That way, round-tripping via toString()
should work fine.
(note also that your conversion to bytes doesn't explicitly specify a character-encoding and is platform-dependent - that could be source of grief further down the line)
XMLBlueprint 7.5 can do the following: - generate sample xml from dtd - generate sample xml from relax ng schema - generate sample xml from xml schema
` Please include either of these:
`#include<sstream>`
using std::istringstream;
Why don't you just use a singleton?
import android.content.Context;
public class ClassicSingleton {
private Context c=null;
private static ClassicSingleton instance = null;
protected ClassicSingleton()
{
// Exists only to defeat instantiation.
}
public void setContext(Context ctx)
{
c=ctx;
}
public Context getContext()
{
return c;
}
public static ClassicSingleton getInstance()
{
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
Then in the activity class:
private ClassicSingleton cs = ClassicSingleton.getInstance();
And in the non activity class:
ClassicSingleton cs= ClassicSingleton.getInstance();
Context c=cs.getContext();
ImageView imageView = (ImageView) ((Activity)c).findViewById(R.id.imageView1);
Using Next.js 9 or above you can get query parameters:
With router
:
import { useRouter } from 'next/router'
const Index = () => {
const router = useRouter()
const {id} = router.query
return(<div>{id}</div>)
}
With getInitialProps
:
const Index = ({id}) => {
return(<div>{id}</div>)
}
Index.getInitialProps = async ({ query }) => {
const {id} = query
return {id}
}
Whenever you change a class in your script, you could use a trigger
to raise your own event.
$(this).addClass('someClass');
$(mySelector).trigger('cssClassChanged')
....
$(otherSelector).bind('cssClassChanged', data, function(){ do stuff });
but otherwise, no, there's no baked-in way to fire an event when a class changes. change()
only fires after focus leaves an input whose input has been altered.
$(function() {_x000D_
var button = $('.clickme')_x000D_
, box = $('.box')_x000D_
;_x000D_
_x000D_
button.on('click', function() { _x000D_
box.removeClass('box');_x000D_
$(document).trigger('buttonClick');_x000D_
});_x000D_
_x000D_
$(document).on('buttonClick', function() {_x000D_
box.text('Clicked!');_x000D_
});_x000D_
});
_x000D_
.box { background-color: red; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="box">Hi</div>_x000D_
<button class="clickme">Click me</button>
_x000D_
Format specifier in printf
should be %f
for doubl
datatypes since float
datatyles eventually convert to double
datatypes inside printf
.
There is no provision to print float
data. Please find the discussion here : Correct format specifier for double in printf