For future searchers. On FreeBSD try the next
pkg_info | grep php5-pdo_mysql
if you see the empty line in return do the following:
cd /usr/ports/databases/php5-pdo_mysql
and the do the install
make install clean
then simply restart your apache and you are done
e.g. sudo /usr/local/etc/rc.d/apache22 restart
Try this tutorial it has the explanation and it will be helpful http://www.ccs.neu.edu/home/kathleen/classes/cs3200/JDBCtutorial.pdf
There is lots of stuff on this topic, each slightly different. Like many users I spent hours trying them and got nowhere. In the end, this is what worked for me - I.e. installed the driver on windows 8.1
In my extras/google/usb_driver is a file android_winusb.inf
I double clicked on this and it "ran" and installed the driver.
I can't explain why this worked.
I was having the same error, but had a proper connection string. My problem was that the driver was not being used, therefore was optimized out of the compiled war.
Be sure to import the driver:
import com.microsoft.sqlserver.jdbc.SQLServerDriver;
And then to force it to be included in the final war, you can do something like this:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
That line is in the original question. This will also work:
SQLServerDriver driver = new SQLServerDriver();
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
Please note that you must install the driver for the version of your software client(MS access) not the version of the OS. that's mean that if your MS Access is a 32-bits version,you must install a 32-bit odbc driver. regards
Windows version:
cd \Program Files\NVIDIA Corporation\NVSMI
nvidia-smi
So I was having this problem, none of the other remedies worked. The error message was opaque, but checking dmesg was key:
[ 10.118255] NVRM: API mismatch: the client has the version 410.79, but
NVRM: this kernel module has the version 384.130. Please
NVRM: make sure that this kernel module and all NVIDIA driver
NVRM: components have the same version.
However I had completely removed the 384 version, and removed any remaining kernel drivers nvidia-384*
. But even after reboot, I was still getting this. Seeing this meant that the kernel was still compiled to reference 384, but was only finding 410. So I recompiled my kernel:
# uname -a # find the kernel it's using
Linux blah 4.13.0-43-generic #48~16.04.1-Ubuntu SMP Thu May 17 12:56:46 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
# update-initramfs -c -k 4.13.0-43-generic #recompile it
# reboot
And then it worked.
After removing 384, I still had 384 files in: /var/lib/dkms/nvidia-XXX/XXX.YY/4.13.0-43-generic/x86_64/module /lib/modules/4.13.0-43-generic/kernel/drivers
I recommend using the locate
command (not installed by default) rather than searching the filesystem every time.
Depending on the device, sometimes you are getting "The folder you specified doesn't contain a compatible software" error because the first interface isn't actually the ADB interface.
Try installing it as a generic "USB composite device" instead (from the 'pick from a list' driver install option); once the standard composite driver installs it will allow Windows to communicate with the device and detect the associated ADB driver interface and install it properly.
To have animation on both ways onHoverIn/Out I did this solution. Hope it will help to someone
@keyframes fadeOutFromBlock {
0% {
position: relative;
opacity: 1;
transform: translateX(0);
}
90% {
position: relative;
opacity: 0;
transform: translateX(0);
}
100% {
position: absolute;
opacity: 0;
transform: translateX(-999px);
}
}
@keyframes fadeInFromNone {
0% {
position: absolute;
opacity: 0;
transform: translateX(-999px);
}
1% {
position: relative;
opacity: 0;
transform: translateX(0);
}
100% {
position: relative;
opacity: 1;
transform: translateX(0);
}
}
.drafts-content {
position: relative;
opacity: 1;
transform: translateX(0);
animation: fadeInFromNone 1s ease-in;
will-change: opacity, transform;
&.hide-drafts {
position: absolute;
opacity: 0;
transform: translateX(-999px);
animation: fadeOutFromBlock 0.5s ease-out;
will-change: opacity, transform;
}
}
The problem with all presented answers it complete lack of taking triggers (and probably other side effects) into account. Solution like
INSERT OR IGNORE ...
UPDATE ...
leads to both triggers executed (for insert and then for update) when row does not exist.
Proper solution is
UPDATE OR IGNORE ...
INSERT OR IGNORE ...
in that case only one statement is executed (when row exists or not).
If you want to pass custom Controller to a form_for while rendering a partial form you can use this:
<%= render 'form', :locals => {:controller => 'my_controller', :action => 'my_action'}%>
and then in the form partial use this local variable like this:
<%= form_for(:post, :url => url_for(:controller => locals[:controller], :action => locals[:action]), html: {class: ""} ) do |f| -%>
Without a bit more code ... its hard to say what's going on.
But if your code looks something like this:
<li routerLinkActive="active">
<a [routerLink]="/categories"><p>Products Categories</p></a>
</li>
...
<router-outlet></router-outlet>
<myComponentA></myComponentA>
<myComponentB></myComponentB>
Then clicking on the router link will route to the categories route and display its template in the router outlet.
Hiding and showing the child components don't affect what is displayed in the router outlet.
So if you click the link again, the categories route is already displayed in the router outlet and it won't display/re-initialize again.
If you could be a bit more specific about what you are trying to do, we could provide more specific suggestions for you. :-)
As also noted in the docs here.
Go to Python X.X/Lib
and add these lines to the site.py
there,
import sys
sys.path.append("yourpathstring")
This changes your sys.path
so that on every load, it will have that value in it..
As stated here about site.py
,
This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.
For other possible methods of adding some path to sys.path
see these docs
AdoptOpenJDK is a new website hosted by the java community. You can find .msi installers for OpenJDK 8 through 14 there, which will perform all the things listed in the question (Unpacking, registry keys, PATH variable updating (and JAVA_HOME), uninstaller...).
This ViewPager only resizes to the current visible children (not the biggest of its actual children)
The idea from https://stackoverflow.com/a/56325869/4718406
public class DynamicHeightViewPager extends ViewPager {
public DynamicHeightViewPager (Context context) {
super(context);
initPageChangeListener();
}
public DynamicHeightViewPager (Context context, AttributeSet attrs) {
super(context, attrs);
initPageChangeListener();
}
private void initPageChangeListener() {
addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
requestLayout();
}
});
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//View child = getChildAt(getCurrentItem());
View child = getCurrentView(this);
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
View getCurrentView(ViewPager viewPager) {
try {
final int currentItem = viewPager.getCurrentItem();
for (int i = 0; i < viewPager.getChildCount(); i++) {
final View child = viewPager.getChildAt(i);
final ViewPager.LayoutParams layoutParams = (ViewPager.LayoutParams)
child.getLayoutParams();
Field f = layoutParams.getClass().getDeclaredField("position");
//NoSuchFieldException
f.setAccessible(true);
int position = (Integer) f.get(layoutParams); //IllegalAccessException
if (!layoutParams.isDecor && currentItem == position) {
return child;
}
}
} catch (NoSuchFieldException e) {
e.fillInStackTrace();
} catch (IllegalArgumentException e) {
e.fillInStackTrace();
} catch (IllegalAccessException e) {
e.fillInStackTrace();
}
return null;
}
}
If you are using impdp command example from @sathyajith-bhat response:
impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;
you will need to use mandatory parameter directory and create and grant it as:
CREATE OR REPLACE DIRECTORY DMP_DIR AS 'c:\Users\USER\Downloads';
GRANT READ, WRITE ON DIRECTORY DMP_DIR TO {USER};
or use one of defined:
select * from DBA_DIRECTORIES;
My ORACLE Express 11g R2 has default named DATA_PUMP_DIR (located at {inst_dir}\app\oracle/admin/xe/dpdump/) you sill need to grant it for your user.
I just did the following (in V 3.5) and it worked like a charm:
<p:column headerText="name" width="20px"/>
body {
background-image: url('../images/background.jpg');
background-repeat: no-repeat;
background-size: cover; /* will auto resize to fill the screen */
}
The standard function atoi()
will likely do what you want.
A simple example using "atoi":
#include <unistd.h>
int main(int argc, char *argv[])
{
int useconds = atoi(argv[1]);
usleep(useconds);
}
If I understood your question, try something like this
declare @dd varchar(50)='Jan 30 2013 12:00:00:000AM'
Select convert(varchar,(CONVERT(date,@dd,103)),103)
Update
SELECT
PREFIX_TableName.ColumnName1 AS Name,
PREFIX_TableName.ColumnName2 AS E-Mail,
convert(varchar,(CONVERT(date,PREFIX_TableName.ColumnName3,103)),103) AS TransactionDate,
PREFIX_TableName.ColumnName4 AS OrderNumber
Easy rule. Start with declaring everything private. And then progress towards the public as the needs arise and design warrants it.
When exposing members ask yourself if you are exposing representation choices or abstraction choices. The first is something you want to avoid as it will introduce too many dependencies on the actual representation rather than on its observable behavior.
As a general rule I try to avoid overriding method implementations by subclassing; it's too easy to screw up the logic. Declare abstract protected methods if you intend for it to be overridden.
Also, use the @Override annotation when overriding to keep things from breaking when you refactor.
If you want to bypass that restriction when fetching the contents with fetch API or XMLHttpRequest in javascript, you can use a proxy server so that it sets the header Access-Control-Allow-Origin
to *
.
const express = require('express');
const request = require('request');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get('/fetch', (req, res) => {
request(
{ url: req.query.url },
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).send('error');
}
res.send(body);
}
)
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));
Above is a sample code( node Js required ) which can act as a proxy server. For eg: If I want to fetch https://www.google.com
normally a CORS error is thrown, but now since the request is sent through the proxy server hosted locally at port 3000, the proxy server adds the Access-Control-Allow-Origin
header in the response and there wont be any issue.
Send a GET request to http://localhost:3000/fetch?url=Your URL here
, instead of directly sending the request to the URl you want to fetch.
Your URL here
stands for the URL you wish to fetch eg: https://www.google.com
This problem can happen when you deploy your web application to a server, so you must check if you already installed MVC3.
Check if the folder C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 3
exists.
If it doesn't exist, you need to install it from http://www.microsoft.com/en-us/download/details.aspx?id=1491
If you wont to install you can add all DLLs locally in bin folder and add references to them this work fine if you host on server don't deploy ASP.NET Web Pages or MVC3.
Consider enumerations. These can be logically broken up for separate use cases.
enum UserDefaultsKeys: String {
case SomeNotification = "aaaaNotification"
case DeviceToken = "deviceToken"
}
enum PhotoMetaKeys: String {
case Orientation = "orientation_hv"
case Size = "size"
case DateTaken = "date_taken"
}
One unique benefit happens when you have a situation of mutually exclusive options, such as:
for (key, value) in photoConfigurationFile {
guard let key = PhotoMetaKeys(rawvalue: key) else {
continue // invalid key, ignore it
}
switch (key) {
case.Orientation: {
photo.orientation = value
}
case.Size: {
photo.size = value
}
}
}
In this example, you will receive a compile error because you have not handled the case of PhotoMetaKeys.DateTaken
.
Kinda late to the party, but in case anyone else is struggling. None of the Google searches I've found for the past two days have come up with anything that works, but I came up with a concise and elegant solution that will always work no matter how many nested tags you have:
function cursor_position() {_x000D_
var sel = document.getSelection();_x000D_
sel.modify("extend", "backward", "paragraphboundary");_x000D_
var pos = sel.toString().length;_x000D_
if(sel.anchorNode != undefined) sel.collapseToEnd();_x000D_
_x000D_
return pos;_x000D_
}_x000D_
_x000D_
// Demo:_x000D_
var elm = document.querySelector('[contenteditable]');_x000D_
elm.addEventListener('click', printCaretPosition)_x000D_
elm.addEventListener('keydown', printCaretPosition)_x000D_
_x000D_
function printCaretPosition(){_x000D_
console.log( cursor_position(), 'length:', this.textContent.trim().length )_x000D_
}
_x000D_
<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>
_x000D_
It selects all the way back to the beginning of the paragraph and then counts the length of the string to get the current position and then undoes the selection to return the cursor to the current position. If you want to do this for an entire document (more than one paragraph), then change paragraphboundary
to documentboundary
or whatever granularity for your case. Check out the API for more details. Cheers! :)
thanks to @usertatha with some modification
function isUUID ( uuid ) {
let s = "" + uuid;
s = s.match('^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$');
if (s === null) {
return false;
}
return true;
}
You can convert the array objects into strings so they can be compared, add the strings to a Set so the comparable duplicates will be automatically removed and then convert each of the strings back into objects.
It might not be as performant as other answers, but it's readable.
const things = {};
things.thing = [];
things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});
const uniqueArray = (arr) => {
const stringifiedArray = arr.map((item) => JSON.stringify(item));
const set = new Set(stringifiedArray);
return Array.from(set).map((item) => JSON.parse(item));
}
const uniqueThings = uniqueArray(things.thing);
console.log(uniqueThings);
It's the same as the Objective-C API, but uses Swift's syntax.
Swift 4.2 & Swift 5:
NotificationCenter.default.addObserver(
self,
selector: #selector(self.batteryLevelChanged),
name: UIDevice.batteryLevelDidChangeNotification,
object: nil)
If your observer does not inherit from an Objective-C object, you must prefix your method with @objc
in order to use it as a selector.
@objc private func batteryLevelChanged(notification: NSNotification){
//do stuff using the userInfo property of the notification object
}
See NSNotificationCenter Class Reference, Interacting with Objective-C APIs
Can someone please tell me how to create a static library from a .cpp and a .hpp file? Do I need to create the .o and the the .a?
Yes.
Create the .o (as per normal):
g++ -c header.cpp
Create the archive:
ar rvs header.a header.o
Test:
g++ test.cpp header.a -o executable_name
Note that it seems a bit pointless to make an archive with just one module in it. You could just as easily have written:
g++ test.cpp header.cpp -o executable_name
Still, I'll give you the benefit of the doubt that your actual use case is a bit more complex, with more modules.
Hope this helps!
Note: This answer addresses part of the problem. For a complete solution (in the form of a library), look at Paul Burke's answer.
You could use the URI to obtain document id
, and then query either MediaStore.Images.Media.EXTERNAL_CONTENT_URI
or MediaStore.Images.Media.INTERNAL_CONTENT_URI
(depending on the SD card situation).
To get document id:
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uriThatYouCurrentlyHave);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
Reference: I'm not able to find the post that this solution is taken from. I wanted to ask the original poster to contribute here. Will look some more tonight.
Here is a more generic solution based on @rindeal solution which does not work on MacOS/BSD (/r
expects a file):
cat << DOC > input.txt
abc
cdef
line
DOC
$ cat << EOF | sed '/^cdef$/ r /dev/stdin' input.txt
line 1
line 2
EOF
# outputs:
abc
cdef
line 1
line 2
line
This can be used to pipe anything into the file at the given position:
$ date | sed '/^cdef$/ r /dev/stdin' input.txt
# outputs
abc
cdef
Tue Mar 17 10:50:15 CET 2020
line
Also, you could add multiple commands which allows deleting the marker line cdef
:
$ date | sed '/^cdef$/ {
r /dev/stdin
d
}' input.txt
# outputs
abc
Tue Mar 17 10:53:53 CET 2020
line
Here is the reason. Starting from Jersey 2.26, Jersey removed HK2 as a hard dependency. It created an SPI as a facade for the dependency injection provider, in the form of the InjectionManager
and InjectionManagerFactory
. So for Jersey to run, we need to have an implementation of the InjectionManagerFactory
. There are two implementations of this, which are for HK2 and CDI. The HK2 dependency is the jersey-hk2
others are talking about.
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.26</version>
</dependency>
The CDI dependency is
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-cdi2-se</artifactId>
<version>2.26</version>
</dependency>
This (jersey-cdi2-se) should only be used for SE environments and not EE environments.
Jersey made this change to allow others to provide their own dependency injection framework. They don't have any plans to implement any other InjectionManager
s, though others have made attempts at implementing one for Guice.
The reason is that the Scanner class is designed for reading in whitespace-separated tokens. It's a convenience class that wraps an underlying input stream. Before scanner all you could do was read in single bytes, and that's a big pain if you want to read words or lines. With Scanner you pass in System.in, and it does a number of read() operations to tokenize the input for you. Reading a single character is a more basic operation. Source
You can use (char) System.in.read();
.
Generally speaking, I tend to use path parameters when there is an obvious 'hierarchy' in the resource, such as:
/region/state/42
If that single resource has a status, one could:
/region/state/42/status
However, if 'region' is not really part of the resource being exposed, it probably belongs as one of the query parameters - similar to pagination (as you mentioned).
127 means command not found
In your case, curl command was not found. Therefore it means, curl was not found.
You need to install/reinstall CURL. That's all. Get latest version for your OS from http://curl.haxx.se/download.html
Close RStudio before installation.
I had the exact same problem and this did the trick for me:
Xcode > Preferences > Accounts > View Details > And just refresh the Provisioning Profile
Seems like the accounts in Xcode were not updated with the latest provisioning profiles so a quick refresh sorted this out.
If you create a tag by e.g.
git tag v1.0
the tag will refer to the most recent commit of the branch you are currently on. You can change branch and create a tag there.
You can also just refer to the other branch while tagging,
git tag v1.0 name_of_other_branch
which will create the tag to the most recent commit of the other branch.
Or you can just put the tag anywhere, no matter which branch, by directly referencing to the SHA1 of some commit
git tag v1.0 <sha1>
I've been using Hamid's answer for a while, but it in cases where the languages array is like ["en", "en-GB", "en-US", "fr-FR", "fr", "en-ZA"] it will return "en", when "en-GB" would be a better match.
My update (below) will return the first long format code e.g. "en-GB", otherwise it will return the first short code e.g. "en", otherwise it will return null.
function getFirstBrowserLanguage() {_x000D_
var nav = window.navigator,_x000D_
browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'],_x000D_
i,_x000D_
language,_x000D_
len,_x000D_
shortLanguage = null;_x000D_
_x000D_
// support for HTML 5.1 "navigator.languages"_x000D_
if (Array.isArray(nav.languages)) {_x000D_
for (i = 0; i < nav.languages.length; i++) {_x000D_
language = nav.languages[i];_x000D_
len = language.length;_x000D_
if (!shortLanguage && len) {_x000D_
shortLanguage = language;_x000D_
}_x000D_
if (language && len>2) {_x000D_
return language;_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
// support for other well known properties in browsers_x000D_
for (i = 0; i < browserLanguagePropertyKeys.length; i++) {_x000D_
language = nav[browserLanguagePropertyKeys[i]];_x000D_
//skip this loop iteration if property is null/undefined. IE11 fix._x000D_
if (language == null) { continue; } _x000D_
len = language.length;_x000D_
if (!shortLanguage && len) {_x000D_
shortLanguage = language;_x000D_
}_x000D_
if (language && len > 2) {_x000D_
return language;_x000D_
}_x000D_
}_x000D_
_x000D_
return shortLanguage;_x000D_
}_x000D_
_x000D_
console.log(getFirstBrowserLanguage());
_x000D_
Update: IE11 was erroring when some properties were undefined. Added a check to skip those properties.
In my case I used blow code for different environment.
document.cookie = name +`=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;Domain=.${document.domain.split('.').splice(1).join('.')}`;
You can set imageview in XML file like this :
<ImageView
android:id="@+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/imagep1" />
and you can define image view in android java file like :
ImageView imageView = (ImageView) findViewById(R.id.imageViewId);
and set Image with drawable like :
imageView.setImageResource(R.drawable.imageFileId);
and set image with your memory folder like :
File file = new File(SupportedClass.getString("pbg"));
if (file.exists()) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap selectDrawable = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
imageView.setImageBitmap(selectDrawable);
}
else
{
Toast.makeText(getApplicationContext(), "File not Exist", Toast.LENGTH_SHORT).show();
}
Consider using CtrlP plug-in.
It is included in Janus Distributive.
Allows you to find files in the current directory, open buffers or most recently used files using "fuzzy matching" or regular expression.
The first line of your subclass' constructor must be a call to super()
to ensure that the constructor of the superclass is called.
DECLARE @id INT
DECLARE @name NVARCHAR(100)
DECLARE @getid CURSOR
SET @getid = CURSOR FOR
SELECT table.id,
table.name
FROM table
WHILE 1=1
BEGIN
FETCH NEXT
FROM @getid INTO @id, @name
IF @@FETCH_STATUS < 0 BREAK
EXEC stored_proc @varName=@id, @otherVarName='test', @varForName=@name
END
CLOSE @getid
DEALLOCATE @getid
//Set Preference
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor;
prefsEditor = myPrefs.edit();
//strVersionName->Any value to be stored
prefsEditor.putString("STOREDVALUE", strVersionName);
prefsEditor.commit();
//Get Preferenece
SharedPreferences myPrefs;
myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String StoredValue=myPrefs.getString("STOREDVALUE", "");
Try this..
You could do this two different ways. One is by using "as"
has_many :tasks, :as => :jobs
or
def jobs
self.tasks
end
Obviously the first one would be the best way to handle it.
I know most people are between deciding whether to use plural or singular. The issue that has not been addressed here is that the client will need to know which one you are using, and they are always likely to make a mistake. This is where my suggestion comes from.
How about both? And by that, I mean use singular for your whole API and then create routes to forward requests made in the plural form to the singular form. For example:
GET /resources = GET /resource
GET /resources/1 = GET /resource/1
POST /resources/1 = POST /resource/1
...
You get the picture. No one is wrong, minimal effort, and the client will always get it right.
I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.
If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany
annotation with the 'mappedBy
' property, it also means that the other side holding the @ManyToOne
annotation with the @JoinColumn
is the 'owner' of this bi-directional relationship.
Also, mappedBy
takes in the instance name (mCustomer
in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).
BONUS :
Also, look into the orphanRemoval
property of @OneToMany
annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.
Try to slightly modify your code:
Sub forEachWs()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns(ws)
Next
End Sub
Sub resizingColumns(ws As Worksheet)
With ws
.Range("A:A").ColumnWidth = 20.14
.Range("B:B").ColumnWidth = 9.71
.Range("C:C").ColumnWidth = 35.86
.Range("D:D").ColumnWidth = 30.57
.Range("E:E").ColumnWidth = 23.57
.Range("F:F").ColumnWidth = 21.43
.Range("G:G").ColumnWidth = 18.43
.Range("H:H").ColumnWidth = 23.86
.Range("i:I").ColumnWidth = 27.43
.Range("J:J").ColumnWidth = 36.71
.Range("K:K").ColumnWidth = 30.29
.Range("L:L").ColumnWidth = 31.14
.Range("M:M").ColumnWidth = 31
.Range("N:N").ColumnWidth = 41.14
.Range("O:O").ColumnWidth = 33.86
End With
End Sub
Note, resizingColumns
routine takes parametr - worksheet to which Ranges belongs.
Basically, when you're using Range("O:O")
- code operats with range from ActiveSheet, that's why you should use With ws
statement and then .Range("O:O")
.
And there is no need to use global variables (unless you are using them somewhere else)
I was able to do this:
String a;
if(rs.getString("column") != null)
{
a = "Hello world!";
}
else
{
a = "Bye world!";
}
Consider using default filter if it is what you need. For example:
{% set host = jabber.host | default(default.host) -%}
or use more fallback values with "hardcoded" one at the end like:
{% set connectTimeout = config.stackowerflow.connect.timeout | default(config.stackowerflow.timeout) | default(config.timeout) | default(42) -%}
if(---------)
printf("hello");
else
printf("hi");
Fill in the blanks so that neither hello nor hi would appear in output.
ans: fclose(stdout)
In my case it was most trivial solution - I just needed to run Vistual Studio as Administrator.
It's trivial thing, but i didn't see this mentioned anywhere.
foo = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
iterator = iter(foo.items())
for i in range(3):
print(next(iterator))
Basically, turn the view (dict_items) into an iterator, and then iterate it with next().
By this way, you hold a form by his ID and throw all his content. This technic is fastiest.
document.forms["id_form"].reset();
Maybe this will help someone. I was using a nested app. project.appname and I actually had project and project.appname in INSTALLED_APPS. Removing project from INSTALLED_APPS allowed the changes to be detected.
In my case I am using a CSS framework which adds box-shadow
, so I had to also add
box-shadow: none;
So the complete snippet is:
border: none;
border-width: 0;
box-shadow: none;
You can using the exists
if (pricePublicList.Exists(x => x.Size == 200))
{
//code
}
You can still use the Screen class from a WPF app. You just need to reference the System.Windows.Forms assembly from your application. Once you've done that, (and referenced System.Drawing for the example below):
Rectangle workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
...works just fine.
Have you considered setting your main window property WindowStartupLocation to CenterScreen?
It depends on various things. But in general algorithms using a Divide-and-Conquer / dichotomic approach will perform well for sorting problems as they present interesting average-case complexities.
To understand which algorithms work best, you will need basic knowledge of algorithms complexity and big-O notation, so you can understand how they rate in terms of average case, best case and worst case scenarios. If required, you'd also have to pay attention to the sorting algorithm's stability.
For instance, usually an efficient algorithm is quicksort. However, if you give quicksort a perfectly inverted list, then it will perform poorly (a simple selection sort will perform better in that case!). Shell-sort would also usually be a good complement to quicksort if you perform a pre-analysis of your list.
Have a look at the following, for "advanced searches" using divide and conquer approaches:
And these more straighforward algorithms for less complex ones:
The above are the usual suspects when getting started, but there are countless others.
As pointed out by R. in the comments and by kriss in his answer, you may want to have a look at HeapSort, which provides a theoretically better sorting complexity than a quicksort (but will won't often fare better in practical settings). There are also variants and hybrid algorithms (e.g. TimSort).
You can use JSON.stringify
, and get some nice indentation as well as perhaps easier to remember syntax.
console.log(JSON.stringify(myObject, null, 4));
{
"a": "a",
"b": {
"c": "c",
"d": {
"e": "e",
"f": {
"g": "g",
"h": {
"i": "i"
}
}
}
}
}
The third argument sets the indentation level, so you can adjust that as desired.
More detail here if needed:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
You need to use wildards (.*
) before and after to replace the whole line:
sed 's/.*TEXT_TO_BE_REPLACED.*/This line is removed by the admin./'
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
For me, it worked as given below:
<div ng-repeat="product in products | filter: { color: 'red'||'blue' }">
<div ng-repeat="product in products | filter: { color: 'red'} | filter: { color:'blue' }">
I made a function out of @arnep 's idea:
echo|set /p="Hello World"
here it is:
:SL (sameline)
echo|set /p=%1
exit /b
Use it with call :SL "Hello There"
I know this is nothing special but it took me so long to think of it I figured I'd post it here.
The solution for me on a CentOS 8 system was checking the System Cryptography Policy by verifying the /etc/crypto-policies/config reads the default value of DEFAULT rather than any other value.
Once changing this value to DEFAULT, run the following command:
/usr/bin/update-crypto-policies --set DEFAULT
Rerun the curl command and it should work.
I have to modify the following files
$CATALINA_BASE/conf/Catalina/localhost/manager.xml
and add following line
<Context privileged="true" antiResourceLocking="false"
docBase="${catalina.home}/webapps/manager">
<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="^.*$" />
</Context>
This will allow tomcat to be accessed from any machine, if you want to grant access to specific IP then use the below value instead of allow="^.*$"
<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="192\.168\.11\.234" />
For those who still getting The magic number in GZip header is not correct. Make sure you are passing in a GZip stream. ERROR and if your string was zipped using php you'll need to do something like:
public static string decodeDecompress(string originalReceivedSrc) {
byte[] bytes = Convert.FromBase64String(originalReceivedSrc);
using (var mem = new MemoryStream()) {
//the trick is here
mem.Write(new byte[] { 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);
mem.Write(bytes, 0, bytes.Length);
mem.Position = 0;
using (var gzip = new GZipStream(mem, CompressionMode.Decompress))
using (var reader = new StreamReader(gzip)) {
return reader.ReadToEnd();
}
}
}
Install Style Loader and CSS Loader:
npm install --save-dev style-loader
npm install --save-dev css-loader
Configure webpack
module: {
loaders: [
{
test: /\.css$/,
loader: 'style-loader'
}, {
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
}
]
}
It's in your home folder but it's hidden by default.
Typing the below commands in the terminal made it visible for me (only the .m2
folder that is, not all the other hidden folders).
> mv ~/.m2 ~/m2
> ln -s ~/m2 ~/.m2
To get the fields info too, you can use the following:
SELECT TABLE_SCHEMA, TABLE_NAME,
COLUMN_NAME, substring(DATA_TYPE, 1,1) AS DATA_TYPE
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA NOT IN("information_schema", "mysql", "performance_schema")
ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION
Just add the column names, yes you can use Null instead but is is a very bad idea to not use column names in any insert, ever.
Dim a As Range, b As Range
Set a = Selection
For Each b In a.Rows
MsgBox b.Address
Next
The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).
For example:
struct foo_t {
int x;
char c;
};
Even though the c
field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8
(on a 32-bit system - rather a system with a 32-bit int
type) because there will need to be 3 bytes of padding after the c
field.
Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.
Before the closing body
tag add this (reference to jQuery library). Other hosted libraries can be found here
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
And this
<script>
//paste your code here
</script>
It should look something like this
<body>
........
........
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script> Your code </script>
</body>
You would need to install pip3.
On Linux, the command would be: sudo apt install python3-pip
On Mac, using brew, first brew install python3
Then brew postinstall python3
Try calling pip3 -V
to see if it worked.
If you are using ngResource, the $resolved attribute of an object is useful for loaders:
For a resource as follows:
var User = $resource('/user/:id', {id:'@id'});
var user = User.get({id: 1})
You can link a loader to the $resolved attribute of the resource object:
<div ng-hide="user.$resolved">Loading ...</div>
You can use this as well
$(document).ready(function(){_x000D_
_x000D_
var currentscroll_position = $(window).scrollTop();_x000D_
$(window).on('scroll', function(){_x000D_
Get_page_scroll_direction();_x000D_
});_x000D_
_x000D_
function Get_page_scroll_direction(){_x000D_
var running_scroll_position = $(window).scrollTop();_x000D_
if(running_scroll_position > currentscroll_position) {_x000D_
_x000D_
$('.direction_value').text('Scrolling Down Scripts');_x000D_
_x000D_
} else {_x000D_
_x000D_
$('.direction_value').text('Scrolling Up Scripts');_x000D_
_x000D_
}_x000D_
currentscroll_position = running_scroll_position;_x000D_
}_x000D_
_x000D_
});
_x000D_
.direction_value{_x000D_
position: fixed;_x000D_
height: 30px;_x000D_
background-color: #333;_x000D_
color: #fff;_x000D_
text-align: center;_x000D_
z-index: 99;_x000D_
left: 0;_x000D_
top: 0;_x000D_
width: 100%;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="direction_value">_x000D_
</div>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
_x000D_
<?php
if (isset($_POST['birthdate'])) {
$timestamp = strtotime($_POST['birthdate']);
$date=date('d',$timestamp);
$month=date('m',$timestamp);
$year=date('Y',$timestamp);
}
?>
confirmed only that method work now:
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + AcMainPage.this.getPackageName() + "&hl=it")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select(".hAyfc .htlgb")
.get(5)
.ownText();
Try wrapping expression with:
$scope.$apply(function() {
$scope.foo.bar=true;
})
Till i understand your question,you want to put two conditions to select a row to be deleted.for that,you need to do:
public void deleteEntry(long row,String key_name) {
db.delete(DATABASE_TABLE, KEY_ROWID + "=" + row + " and " + KEY_NAME + "=" + key_name, null);
/*if you just have key_name to select a row,you can ignore passing rowid(here-row) and use:
db.delete(DATABASE_TABLE, KEY_NAME + "=" + key_name, null);
*/
}
You don't say what platform you're targeting. Referring to tables as files, though, leads me to believe that you're NOT running DB2 on Linux, UNIX or Windows (LUW).
However, if you are on DB2 LUW, see the MERGE statement:
For your example statement, this would be written as:
merge into file1 a
using (select anotherfield, something from file2) b
on substr(a.firstfield,10,20) = substr(b.anotherfield,1,10)
when matched and a.firstfield like 'BLAH%'
then update set a.firstfield = 'BIT OF TEXT' || b.something;
Please note: For DB2, the third argument of the SUBSTR function is the number of bytes to return, not the ending position. Therefore, SUBSTR(a.firstfield,10,20) returns CHAR(20). However, SUBSTR(b.anotherfield,1,10) returns CHAR(10). I'm not sure if this was done on purpose, but it may affect your comparison.
My reason for the Code 1 was that the target folder was read only. Hope this helps someone! I had a post build event to do a copy from one directory to another and the destination was read only. So I just went and unchecked the read-only attribute on the directory and all its subdirectories! Just make sure that its a directory that's safe to do so!
Try to change like this ..
firstStr = "<?xml version" 'my file always starts like this
Do until objInputFile.AtEndOfStream
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))
tmpStr = objInputFile.ReadLine
If InStr(tmpStr, substrToFind) <= 0 Then
If Instr(tmpStr, firstStr) > 0 Then
text = tmpStr 'to avoid the first empty line
Else
text = text & vbCrLf & tmpStr
End If
Else
text = text & vbCrLf & strToAdd & vbCrLf & tmpStr
End If
index = index + 1
Loop
Sometimes it may be required to execute the update atomically that is using one update request to the database without reading it first.
Also get
-set attribute
-save
may cause problems if such updates may be done concurrently or if you need to set the new value based on the old field value.
In such cases query expressions together with update
may by useful:
TemperatureData.objects.filter(id=1).update(value=F('value') + 1)
RTM
From the docs for the Python random
module:
Functions for integers:
random.randrange(stop)
random.randrange(start, stop[, step])
Return a randomly selected element from range(start, stop, step).
This is equivalent to choice(range(start, stop, step)), but doesn’t
actually build a range object.
That explains why it only gives you 0, doesn't it. range(0,1)
is [0]
. It is choosing from a list consisting of only that value.
Also from those docs:
random.random()
Return the next random floating point number in the range [0.0, 1.0).
But if your inclusion of the numpy
tag is intentional, you can generate many random floats in that range with one call using a np.random
function.
It's easy to do. The cURL code that's on the page that Elad Nava has put here works. Elad has commented about the error he's receiving.
String describing an error that occurred while processing the message for that recipient. The possible values are the same as documented in the above table, plus "Unavailable" (meaning GCM servers were busy and could not process the message for that particular recipient, so it could be retried).
I've got a service set up already that seems to be working (ish), and so far all I've had back are unavailable returns from Google. More than likely this will change soon.
To answer the question, use PHP, make sure the Zend Framework is in your include path, and use this code:
<?php
ini_set('display_errors',1);
include"Zend/Loader/Autoloader.php";
Zend_Loader_Autoloader::getInstance();
$url = 'https://android.googleapis.com/gcm/send';
$serverApiKey = "YOUR API KEY AS GENERATED IN API CONSOLE";
$reg = "DEVICE REGISTRATION ID";
$data = array(
'registration_ids' => array($reg),
'data' => array('yourname' => 'Joe Bloggs')
);
print(json_encode($data));
$client = new Zend_Http_Client($url);
$client->setMethod('POST');
$client->setHeaders(array("Content-Type" => "application/json", "Authorization" => "key=" . $serverApiKey));
$client->setRawData(json_encode($data));
$request = $client->request('POST');
$body = $request->getBody();
$headers = $request->getHeaders();
print("<xmp>");
var_dump($body);
var_dump($headers);
And there we have it. A working (it will work soon) example of using Googles new GCM in Zend Framework PHP.
You can do this way, providing Json or Any other variable:
1) For exemple, in the controller, you can use Json.NET
to provide Json
to the ViewBag
:
ViewBag.Number = 10;
ViewBag.FooObj = JsonConvert.SerializeObject(new Foo { Text = "Im a foo." });
2) In the View
, put the script like this at the bottom of the page.
<script type="text/javascript">
var number = parseInt(@ViewBag.Number); //Accessing the number from the ViewBag
alert("Number is: " + number);
var model = @Html.Raw(@ViewBag.FooObj); //Accessing the Json Object from ViewBag
alert("Text is: " + model.Text);
</script>
You are reading this answer says that your __init__.py
is in the right place, you have installed all the dependencies and you are still getting the ImportError
.
I was facing a similar issue except that my program would run fine when ran using PyCharm but the above error when I would run it from the terminal. After digging further, I found out that PYTHONPATH
didn't have the entry for the project directory. So, I set PYTHONPATH
per Import statement works on PyCharm but not from terminal:
export PYTHONPATH=$PYTHONPATH:`pwd` (OR your project root directory)
There's another way to do this using sys.path
as:
import sys
sys.path.insert(0,'<project directory>') OR
sys.path.append('<project directory>')
You can use insert/append based on the order in which you want your project to be searched.
You can use the V3 API to get a raw file like this (you'll need an OAuth token):
curl -H 'Authorization: token INSERTACCESSTOKENHERE' -H 'Accept: application/vnd.github.v3.raw' -O -L https://api.github.com/repos/*owner*/*repo*/contents/*path*
All of this has to go on one line. The -O
option saves the file in the current directory. You can use -o filename
to specify a different filename.
To get the OAuth token follow the instructions here: https://help.github.com/articles/creating-an-access-token-for-command-line-use
I've written this up as a gist as well: https://gist.github.com/madrobby/9476733
The Why
java.util.logging has a root logger that defaults to Level.INFO
, and a ConsoleHandler attached to it that also defaults to Level.INFO
.
FINE
is lower than INFO
, so fine messages are not displayed by default.
Solution 1
Create a logger for your whole application, e.g. from your package name or use Logger.getGlobal()
, and hook your own ConsoleLogger to it.
Then either ask root logger to shut up (to avoid duplicate output of higher level messages), or ask your logger to not forward logs to root.
public static final Logger applog = Logger.getGlobal();
...
// Create and set handler
Handler systemOut = new ConsoleHandler();
systemOut.setLevel( Level.ALL );
applog.addHandler( systemOut );
applog.setLevel( Level.ALL );
// Prevent logs from processed by default Console handler.
applog.setUseParentHandlers( false ); // Solution 1
Logger.getLogger("").setLevel( Level.OFF ); // Solution 2
Solution 2
Alternatively, you may lower the root logger's bar.
You can set them by code:
Logger rootLog = Logger.getLogger("");
rootLog.setLevel( Level.FINE );
rootLog.getHandlers()[0].setLevel( Level.FINE ); // Default console handler
Or with logging configuration file, if you are using it:
.level = FINE
java.util.logging.ConsoleHandler.level = FINE
By lowering the global level, you may start seeing messages from core libraries, such as from some Swing or JavaFX components. In this case you may set a Filter on the root logger to filter out messages not from your program.
It Works
To find master page controls on Child page
Label lbl_UserName = this.Master.FindControl("lbl_UserName") as Label;
lbl_UserName.Text = txtUsr.Text;
This is very late but i like to share my experience this same issue. i face the same issue in Android studio i tried to some other solution that i found in internet but nothing works for me unless i REBUILD THE PROJECT and it solve my issue.
Hope this will works for you too.
Happy coding.
Here's a simpler answer for the ASP.NET Core Web Api/Swashbuckle combo, that doesn't require you to register any custom filters. Third time's a charm you know :).
Adding the code below to your Swagger config will cause the Authorize button to appear, allowing you to enter a bearer token to be sent for all requests. Don't forget to enter this token as Bearer <your token here>
when asked.
Note that the code below will send the token for any and all requests and operations, which may or may not be what you want.
services.AddSwaggerGen(c =>
{
//...
c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "Bearer", new string[] { } }
});
//...
}
Via this thread.
I tried this on Mac OSX with Chrome 42.0.2311.90 (64-bit) and this works by using CMD + /
The version of the notebook server is 3.1.0-cbccb68 and is running on:
Python 2.7.9 |Anaconda 2.1.0 (x86_64)| (default, Dec 15 2014, 10:37:34)
[GCC 4.2.1 (Apple Inc. build 5577)]
Could it be a browser related problem? Did you try Firefox or IE?
purrr::compose()
is another quick way to define this for later use, as in:
`%!in%` <- compose(`!`, `%in%`)
Your getAll()
method does not get all. It returns the first car.
The return
statement terminates the loop.
Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.
So, first build a list, then use pickle.dump
to send it to a file...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
>>> import pickle
>>>
>>> with open('parrot.pkl', 'wb') as f:
... pickle.dump(mylist, f)
...
>>>
Then quit and come back later… and open with pickle.load
...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
... mynewlist = pickle.load(f)
...
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
You need to declare the variables outside the function:
Public iRaw As Integer
Public iColumn As Integer
Function find_results_idle()
iRaw = 1
iColumn = 1
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them. Let's begin with giving the checkboxes a class so we can round them up very nicely. I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true. the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
.c_str()
returns a const char*
. If you need a mutable version, you will need to produce a copy yourself.
Using the property of String
double value = 123.456789;
String.Format("{0:0.00}", value);
Note: This can be used to display only.
Using System.Math
double value = 123.456789;
System.Math.Round(value, 2);
redirect to ../
If you are using SQL 2005 you can do something like this...
SELECT rs.Field1,rs.Field2
FROM (
SELECT Field1,Field2, Rank()
over (Partition BY Section
ORDER BY RankCriteria DESC ) AS Rank
FROM table
) rs WHERE Rank <= 10
If your RankCriteria has ties then you may return more than 10 rows and Matt's solution may be better for you.
No - it doesn't matter in the slightest. On NT the .bat and .cmd extension both cause the cmd.exe processor to process the file in exactly the same way.
Additional interesting information about command.com vs. cmd.exe on WinNT-class systems from MS TechNet (http://technet.microsoft.com/en-us/library/cc723564.aspx):
This behavior reveals a quite subtle feature of Windows NT that is very important. The 16-bit MS-DOS shell (COMMAND.COM) that ships with Windows NT is specially designed for Windows NT. When a command is entered for execution by this shell, it does not actually execute it. Instead, it packages the command text and sends it to a 32-bit CMD.EXE command shell for execution. Because all commands are actually executed by CMD.EXE (the Windows NT command shell), the 16-bit shell inherits all the features and facilities of the full Windows NT shell.
You can just put:
header("HTTP/1.0 500 Internal Server Error");
inside your conditions like:
if (that happened) {
header("HTTP/1.0 500 Internal Server Error");
}
As for the database query, you can just do that like this:
$result = mysql_query("..query string..") or header("HTTP/1.0 500 Internal Server Error");
You should remember that you have to put this code before any html tag (or output).
To remove the upstream for the current branch do:
$ git branch --unset-upstream
This is available for Git v.1.8.0 or newer. (Sources: 1.7.9 ref, 1.8.0 ref)
My current solution is the following (with RTTI disabled - you could use std::type_index, too):
#include <type_traits>
#include <iostream>
#include <tuple>
class Type
{
};
template<typename T>
class TypeImpl : public Type
{
};
template<typename T>
inline Type* typeOf() {
static Type* typePtr = new TypeImpl<T>();
return typePtr;
}
/* ------------- */
template<
typename Calling
, typename Result = void
, typename From
, typename Action
>
inline Result DoComplexDispatch(From* from, Action&& action);
template<typename Cls>
class ChildClasses
{
public:
using type = std::tuple<>;
};
template<typename... Childs>
class ChildClassesHelper
{
public:
using type = std::tuple<Childs...>;
};
//--------------------------
class A;
class B;
class C;
class D;
template<>
class ChildClasses<A> : public ChildClassesHelper<B, C, D> {};
template<>
class ChildClasses<B> : public ChildClassesHelper<C, D> {};
template<>
class ChildClasses<C> : public ChildClassesHelper<D> {};
//-------------------------------------------
class A
{
public:
virtual Type* GetType()
{
return typeOf<A>();
}
template<
typename T,
bool checkType = true
>
/*virtual*/void DoVirtualGeneric()
{
if constexpr (checkType)
{
return DoComplexDispatch<A>(this, [&](auto* other) -> decltype(auto)
{
return other->template DoVirtualGeneric<T, false>();
});
}
std::cout << "A";
}
};
class B : public A
{
public:
virtual Type* GetType()
{
return typeOf<B>();
}
template<
typename T,
bool checkType = true
>
/*virtual*/void DoVirtualGeneric() /*override*/
{
if constexpr (checkType)
{
return DoComplexDispatch<B>(this, [&](auto* other) -> decltype(auto)
{
other->template DoVirtualGeneric<T, false>();
});
}
std::cout << "B";
}
};
class C : public B
{
public:
virtual Type* GetType() {
return typeOf<C>();
}
template<
typename T,
bool checkType = true
>
/*virtual*/void DoVirtualGeneric() /*override*/
{
if constexpr (checkType)
{
return DoComplexDispatch<C>(this, [&](auto* other) -> decltype(auto)
{
other->template DoVirtualGeneric<T, false>();
});
}
std::cout << "C";
}
};
class D : public C
{
public:
virtual Type* GetType() {
return typeOf<D>();
}
};
int main()
{
A* a = new A();
a->DoVirtualGeneric<int>();
}
// --------------------------
template<typename Tuple>
class RestTuple {};
template<
template<typename...> typename Tuple,
typename First,
typename... Rest
>
class RestTuple<Tuple<First, Rest...>> {
public:
using type = Tuple<Rest...>;
};
// -------------
template<
typename CandidatesTuple
, typename Result
, typename From
, typename Action
>
inline constexpr Result DoComplexDispatchInternal(From* from, Action&& action, Type* fromType)
{
using FirstCandidate = std::tuple_element_t<0, CandidatesTuple>;
if constexpr (std::tuple_size_v<CandidatesTuple> == 1)
{
return action(static_cast<FirstCandidate*>(from));
}
else {
if (fromType == typeOf<FirstCandidate>())
{
return action(static_cast<FirstCandidate*>(from));
}
else {
return DoComplexDispatchInternal<typename RestTuple<CandidatesTuple>::type, Result>(
from, action, fromType
);
}
}
}
template<
typename Calling
, typename Result
, typename From
, typename Action
>
inline Result DoComplexDispatch(From* from, Action&& action)
{
using ChildsOfCalling = typename ChildClasses<Calling>::type;
if constexpr (std::tuple_size_v<ChildsOfCalling> == 0)
{
return action(static_cast<Calling*>(from));
}
else {
auto fromType = from->GetType();
using Candidates = decltype(std::tuple_cat(std::declval<std::tuple<Calling>>(), std::declval<ChildsOfCalling>()));
return DoComplexDispatchInternal<Candidates, Result>(
from, std::forward<Action>(action), fromType
);
}
}
The only thing I don't like is that you have to define/register all child classes.
The query below will result in dd-mmm-yy format.
select
cast(DAY(getdate()) as varchar)+'-'+left(DATEname(m,getdate()),3)+'-'+
Right(Year(getdate()),2)
<button onClick="abrirOpen()">Open Dialog</button>
<script type="text/javascript">
var $dialogo = $("<div></div>").html("Aqui tu contenido(here your content)").dialog({
title: "Dialogo de UI",
autoOpen: false,
close: function(ev, ui){
$(this).dialog("destroy");
}
function abrirOpen(){
$dialogo.dialog("open");
}
});
//**Esto funciona para mi... (this works for me)**
</script>
Change the code where you load the partial view to:
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable
In case you need this to write a .properties
file you can just add the Strings into a Properties object and then save it to a file. It will take care for the conversion.
extern "C"
doesn't change the presence or absence of the __cplusplus
macro. It just changes the linkage and name-mangling of the wrapped declarations.
You can nest extern "C"
blocks quite happily.
If you compile your .c
files as C++ then anything not in an extern "C"
block, and without an extern "C"
prototype will be treated as a C++ function. If you compile them as C then of course everything will be a C function.
Yes
You can safely mix C and C++ in this way.
outI used a directive. Here is the code:
app.directive('onBlurVal', function () {
return {
restrict: 'A',
link: function (scope, element, attrs, controller) {
element.on('focus', function () {
element.next().removeClass('has-visited');
element.next().addClass('has-focus');
});
element.on('blur', function () {
element.next().removeClass('has-focus');
element.next().addClass('has-visited');
});
}
}
})
All my input control has a span element as the next element, which is where my validation message is displayed and so the directive as an attribute is added to each input control.
I also have (optional).has-focus and has-visited css class in my css file which you see being referenced in the directive.
NOTE: remember to add 'on-blur-val' exactly this way to your input control without the apostrophes
Use display:table-cell;
for removing space between .Left and .Right
div.left {_x000D_
background:blue;_x000D_
height:200px;_x000D_
width:300px;_x000D_
}_x000D_
_x000D_
div.right{_x000D_
background:green;_x000D_
height:300px;_x000D_
width:100px;_x000D_
}_x000D_
_x000D_
.container{_x000D_
background:black;_x000D_
height:400px;_x000D_
width:450px;_x000D_
}_x000D_
_x000D_
.container > div {_x000D_
display: table-cell;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>_x000D_
<div class="left">_x000D_
LEFT_x000D_
</div>_x000D_
</div>_x000D_
<div>_x000D_
<div class="right">_x000D_
RIGHT_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
I have been trying out the different packages including the function:
install.packages ("prettyR")
library (prettyR)
delimit.table (Corrvar,"Name the csv.csv")
## Corrvar
is a name of an object from an output I had on scaled variables to run a regression.
However I tried this same code for an output from another analysis (occupancy models model selection output) and it did not work. And after many attempts and exploration I:
In the "Data" vignette, click on "Text to column"
Select Delimited option, click next
Tick space box in "Separator", click next
Click Finalize (End)
Your output now should be in a form you can manipulate easy in excel. So perhaps not the fanciest option but it does the trick if you just want to explore your data in another way.
PS. If the labels in excel are not the exact one it is because Im translating the lables from my spanish excel.
//$sql - sql statement
//$em - entity manager
$em->getConnection()->exec( $sql );
you should be searching about how to add favicon.ico
. You can try adding favicon.ico
directly in your html pages like this
<link rel="shortcut icon" href="/favicon.png" type="image/png">
<link rel="shortcut icon" type="image/png" href="http://www.example.com/favicon.png" />
Or you can update that in your webserver
. It is advised to add in your webserver
as you don't need to add this in each of your html
pages (assuming no includes
).
To add in your apache
place the favicon.ico
in your root website director and add this in httpd.conf
AddType image/x-icon .ico
You can use
filter: brightness(0) invert(1);
html {_x000D_
background: red;_x000D_
}_x000D_
p {_x000D_
float: left;_x000D_
max-width: 50%;_x000D_
text-align: center;_x000D_
}_x000D_
img {_x000D_
display: block;_x000D_
max-width: 100%;_x000D_
}_x000D_
.filter {_x000D_
-webkit-filter: brightness(0) invert(1);_x000D_
filter: brightness(0) invert(1);_x000D_
}
_x000D_
<p>_x000D_
Original:_x000D_
<img src="http://i.stack.imgur.com/jO8jP.gif" />_x000D_
</p>_x000D_
<p>_x000D_
Filter:_x000D_
<img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />_x000D_
</p>
_x000D_
First, brightness(0)
makes all image black, except transparent parts, which remain transparent.
Then, invert(1)
makes the black parts white.
There is no problem in deleting this. It's not only the WebStorm IDE creating this file, but also PhpStorm and all other of JetBrains' IDEs.
It is safe to delete it but if your project is from GitLab or GitHub then you will see a warning.
In the first situation, Num2
is extending the class Num
and since you are not redefining the special method named __init__()
in Num2
, it gets inherited from Num
.
When a class defines an
__init__()
method, class instantiation automatically invokes__init__()
for the newly-created class instance.
In the second situation, since you are redefining __init__()
in Num2
you need to explicitly call the one in the super class (Num
) if you want to extend its behavior.
class Num2(Num):
def __init__(self,num):
Num.__init__(self,num)
self.n2 = num*2
I did something else. I wanted to replace a word, in lists off lists, that contained phrases. I wanted to replace that sttring / word with a new word that will be a join between string and number, and that number / digit will indicate the position of the phrase / sublist / lists of lists.
That is, I replaced a string with a string and an incremental number that follow it.
myoldlist_1=[[' myoldword'],[''],['tttt myoldword'],['jjjj ddmyoldwordd']]
No_ofposition=[]
mynewlist_2=[]
for i in xrange(0,4,1):
mynewlist_2.append([x.replace('myoldword', "%s" % i+"_mynewword") for x in myoldlist_1[i]])
if len(mynewlist_2[i])>0:
No_ofposition.append(i)
mynewlist_2
No_ofposition
You need to set the text to something other than an empty string. In addition, the .html() function should do it while preserving the HTML structure of the div.
$('#one').html($('#one').html().replace('text','replace'));
i'd use a simple one line comparisant for these use cases
$username = trim($_POST['userName'])?:'Anonymous';
This is for the use case you are certain error logging is off so you don't get a warning that the variable isn't initialised.
this is the paranoid version:
$username = !empty(trim(isset($_POST['userName'])?$_POST['userName']:''))?$_POST['userName']:'Anonymous';
This implements a check if the $_POST
variable is set. before accessing it.
Another option is
>>> print os.path.relpath('/usr/var/log/', '/usr/var')
log
The folder being password protected has nothing to do with PHP!
The method being used is called "Basic Authentication". There are no cross-browser ways to "logout" from it, except to ask the user to close and then open their browser...
Here's how you you could do it in PHP instead (fully remove your Apache basic auth in .htaccess
or wherever it is first):
login.php:
<?php
session_start();
//change 'valid_username' and 'valid_password' to your desired "correct" username and password
if (! empty($_POST) && $_POST['user'] === 'valid_username' && $_POST['pass'] === 'valid_password')
{
$_SESSION['logged_in'] = true;
header('Location: /index.php');
}
else
{
?>
<form method="POST">
Username: <input name="user" type="text"><br>
Password: <input name="pass" type="text"><br><br>
<input type="submit" value="submit">
</form>
<?php
}
index.php
<?php
session_start();
if (! empty($_SESSION['logged_in']))
{
?>
<p>here is my super-secret content</p>
<a href='logout.php'>Click here to log out</a>
<?php
}
else
{
echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
}
logout.php:
<?php
session_start();
session_destroy();
echo 'You have been logged out. <a href="/">Go back</a>';
Obviously this is a very basic implementation. You'd expect the usernames and passwords to be in a database, not as a hardcoded comparison. I'm just trying to give you an idea of how to do the session thing.
Hope this helps you understand what's going on.
This is also an option
for key, element := range myMap{
fmt.Println("Key:", key, "Element:", element)
}
"SET serveroutput ON" is a SQL*Plus command and is not valid PL/SQL.
What is the "Visual C#"? There is no such thing. Just C#, or .NET C# :)
Also, Python's convention for constants CONSTANT_NAME
is not very common in C#. We are usually using CamelCase according to MSDN standards, e.g. public const string ExtractedMagicString = "vs2019";
Source: Defining constants in C#
Here is a working example of above. http://jsfiddle.net/z7L6m2sc/ Now select2 has been updated the classes have change may be why you cannot get it to work. Here is the css....
.select2-dropdown.select2-dropdown--below{
width: 148px !important;
}
.select2-container--default .select2-selection--single{
padding:6px;
height: 37px;
width: 148px;
font-size: 1.2em;
position: relative;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
background-image: -moz-linear-gradient(top, #424242, #030303);
background-image: -ms-linear-gradient(top, #424242, #030303);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
background-image: -webkit-linear-gradient(top, #424242, #030303);
background-image: -o-linear-gradient(top, #424242, #030303);
background-image: linear-gradient(#424242, #030303);
width: 40px;
color: #fff;
font-size: 1.3em;
padding: 4px 12px;
height: 27px;
position: absolute;
top: 0px;
right: 0px;
width: 20px;
}
For me this happened when I updated Python 64 bit from 3.6.4 to 3.6.5. It threw some error like "unable to extract python.dll. Do you have permissions."
Pycharm also failed to load interpreter, even though I reloaded it in settings. Running python
command gave same error, with and without administrator mode.
There was error in installation of Python, include folder in python installation directory C:\Users\USERNAME\AppData\Local\Programs\Python\Python36 was missing
Reinstalling Python also dint solve the issue.(Not removal and install)
Uninstall Python and Install of Python again.
Because running installer was just extracting same files excluding include folder
Who knows if you still need it, but here is the solution.
Once you get to the --slurp
option, it's easy!
--slurp/-s:
Instead of running the filter for each JSON object in the input,
read the entire input stream into a large array and run the filter just once.
Then the +
operator will do what you want:
jq -s '.[0] + .[1]' config.json config-user.json
(Note: if you want to merge inner objects instead of just overwriting the left file ones with the right file ones, you will need to do it manually)
Try this code.
For showing Softkeyboard:
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
For Hiding SoftKeyboard -
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
Just use HTML5, input type=”number”
Thank you everyone, for all your precise replys.
Using the svg in a shadow dom, I add the 3 linear gradients I need within the svg, inside a . I place the css fill rule on the web component and the inheritance od fill does the job.
<svg viewbox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
<path
d="m258 0c-45 0-83 38-83 83 0 45 37 83 83 83 45 0 83-39 83-84 0-45-38-82-83-82zm-85 204c-13 0-24 10-24 23v48c0 13 11 23 24 23h23v119h-23c-13 0-24 11-24 24l-0 47c0 13 11 24 24 24h168c13 0 24-11 24-24l0-47c0-13-11-24-24-24h-21v-190c0-13-11-23-24-23h-123z"></path>
</svg>
<svg height="0" width="0">
<defs>
<linearGradient id="lgrad-p" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#4169e1"></stop><stop offset="99%" stop-color="#c44764"></stop></linearGradient>
<linearGradient id="lgrad-s" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#ef3c3a"></stop><stop offset="99%" stop-color="#6d5eb7"></stop></linearGradient>
<linearGradient id="lgrad-g" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#585f74"></stop><stop offset="99%" stop-color="#b6bbc8"></stop></linearGradient>
</defs>
</svg>
<div></div>
<style>
:first-child {
height:150px;
width:150px;
fill:url(#lgrad-p) blue;
}
div{
position:relative;
width:150px;
height:150px;
fill:url(#lgrad-s) red;
}
</style>
<script>
const shadow = document.querySelector('div').attachShadow({mode: 'open'});
shadow.innerHTML="<svg viewbox=\"0 0 512 512\">\
<path d=\"m258 0c-45 0-83 38-83 83 0 45 37 83 83 83 45 0 83-39 83-84 0-45-38-82-83-82zm-85 204c-13 0-24 10-24 23v48c0 13 11 23 24 23h23v119h-23c-13 0-24 11-24 24l-0 47c0 13 11 24 24 24h168c13 0 24-11 24-24l0-47c0-13-11-24-24-24h-21v-190c0-13-11-23-24-23h-123z\"></path>\
</svg>\
<svg height=\"0\">\
<defs>\
<linearGradient id=\"lgrad-s\" gradientTransform=\"rotate(75)\"><stop offset=\"45%\" stop-color=\"#ef3c3a\"></stop><stop offset=\"99%\" stop-color=\"#6d5eb7\"></stop></linearGradient>\
<linearGradient id=\"lgrad-g\" gradientTransform=\"rotate(75)\"><stop offset=\"45%\" stop-color=\"#585f74\"></stop><stop offset=\"99%\" stop-color=\"#b6bbc8\"></stop></linearGradient>\
</defs>\
</svg>\
";
</script>
_x000D_
The first one is normal SVG, the second one is inside a shadow dom.
There's a new way to do this coming in Python 3.4:
from contextlib import suppress
with suppress(Exception):
# your code
Here's the commit that added it: http://hg.python.org/cpython/rev/406b47c64480
And here's the author, Raymond Hettinger, talking about this and all sorts of other Python hotness (relevant bit at 43:30): http://www.youtube.com/watch?v=OSGv2VnC0go
If you wanted to emulate the bare except
keyword and also ignore things like KeyboardInterrupt
—though you usually don't—you could use with suppress(BaseException)
.
Edit: Looks like ignored
was renamed to suppress
before the 3.4 release.
Here is a very short solution that doesn't use the deprecated keyCode
or which
, doesn't block any non input keys, and uses pure javascript. (Tested in Chromium 70.0.3533, Firefox 62.0, and Edge 42.17134.1.0)
HTML:
<input type="text" onkeypress="validate(event)">
JS:
function validate(ev) {
if (!ev) {
ev = window.event;
}
if (!ev.ctrlKey && ev.key.length === 1 && (isNaN(+ev.key) || ev.key === " ")) {
return ev.preventDefault();
}
}
it's because some of the fields (specifically InvoiceID on the Invoices table and on the InvoiceLineItems) are present on both table. The way to answer of question is to add an ALIAS
on it.
SELECT
a.VendorName, Invoices.InvoiceID, .. -- or use full tableName
FROM Vendors a -- This is an `ALIAS` of table Vendors
JOIN Invoices ON (Vendors.VendorID = Invoices.VendorID)
JOIN InvoiceLineItems ON (Invoices.InvoiceID = InvoiceLineItems.InvoiceID)
WHERE
Invoices.InvoiceID IN
(SELECT InvoiceSequence
FROM InvoiceLineItems
WHERE InvoiceSequence > 1)
ORDER BY
VendorName, InvoiceID, InvoiceSequence, InvoiceLineItemAmount
sort -nk2 file.txt
Accordingly you can change column number.
If you are using Rails
(or a standalone ActiveSupport
), starting from version 6.1
, there is a compact_blank
method which removes blank
values from hashes.
It uses Object#blank?
under the hood for determining if an item is blank.
{ a: "", b: 1, c: nil, d: [], e: false, f: true }.compact_blank
# => { b: 1, f: true }
Here is a link to the docs and a link to the relative PR.
A destructive variant is also available. See Hash#compact_blank!
.
If you need to remove only nil
values,
please, consider using Ruby build-in Hash#compact
and Hash#compact!
methods.
{ a: 1, b: false, c: nil }.compact
# => { a: 1, b: false }
document.getElementById("something").innerHTML = "<img src=\"something\" onmouseover=\"change('ex1')\" />";
OR
document.getElementById("something").innerHTML = '<img src="something" onmouseover="change(\'ex1\')" />';
It should be working...
$remove= "strawberry";
$array = ["apple", "orange", "strawberry", "blueberry", "kiwi"];
foreach ($array as $key => $value) {
if ($value!=$remove) {
echo $value.'<br/>';
continue;
}
}
I've created a little Powershell function to emulate MSDOS pause
. This handles whether running Powershell ISE or non ISE. (ReadKey
does not work in powershell ISE). When running Powershell ISE, this function opens a Windows MessageBox
. This can sometimes be confusing, because the MessageBox
does not always come to the forefront. Anyway, here it goes:
Usage:
pause "Press any key to continue"
Function definition:
Function pause ($message)
{
# Check if running Powershell ISE
if ($psISE)
{
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show("$message")
}
else
{
Write-Host "$message" -ForegroundColor Yellow
$x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
}
None of the above worked for me for some reason :/, so I added an element ref to a top element in app.component.html
, and (activate)=onNavigate($event)
to the router-outlet
.
<!--app.component.html-->
<div #topScrollAnchor></div>
<app-navbar></app-navbar>
<router-outlet (activate)="onNavigate($event)"></router-outlet>
Then I added the child to the app.component.ts file to the type of ElementRef
, and had it scroll to it on activation of the router-outlet.
export class AppComponent {
@ViewChild('topScrollAnchor') topScroll: ElementRef;
onNavigate(event): any {
this.topScroll.nativeElement.scrollIntoView({ behavior: 'smooth' });
}
}
Here's the code in stackblitz
if you need to remove the first leter of string
string.slice(1, 0)
and for remove last letter
string.slice(0, -1)
Depending on your exact requirements, you may do best with a jagged array of sorts with:
List<string>[] results = new { new List<string>(), new List<string>() };
Or you may do well with a list of lists or some other such construct.
You could use the legend's set_visible
method:
ax.legend().set_visible(False)
draw()
This is based on a answer provided to me in response to a similar question I had some time ago here
(Thanks for that answer Jouni - I'm sorry I was unable to mark the question as answered... perhaps someone who has the authority can do so for me?)
All answers here are still using the FormData API. It is like a "multipart/form-data"
upload without a form. You can also upload the file directly as content inside the body of the POST
request using xmlHttpRequest
like this:
var xmlHttpRequest = new XMLHttpRequest();
var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...
xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);
Content-Type
and Content-Disposition
headers are used for explaining what we are sending (mime-type and file name).
I posted similar answer also here.
Java Primitive Specializations Generator supports /* with */
, /* define */
and /* if */ ... /* elif */ ... /* endif */
blocks which allow to do some kind of macro generation in Java code, similar to java-comment-preprocessor mentioned in this answer.
JPSG has Maven and Gradle plugins.
Since Android Studio 3.2 and Android Emulator 27.3.8 - the android emulator is supported by Windows Hypervisor Platform and as stated in the official android developer blog - there is mac support (since OS X v10.10 Yosemite) and windows support (since April 2018 Update). You may find further instructions on the developer blog.
In my opinion, the performance is significantly better than all previous workarounds.
I had the same problem and found out Folding can be enabled or disabled, and in my case got disabled somehow.
To solve it, simply right click on the line numbers/breakpoint section (vertical bar in the left of the editor), then under the 'Folding' section chose 'Enable folding'.
ctrlshift/ should be working fine after.
While the accepted answer is correct, I'll add a more elegant version (in my opinion):
boolean idExists = tabPane.getTabs().stream()
.map(Tab::getId)
.anyMatch(idToCheck::equals);
Don't neglect using Stream#map() which allows to flatten the data structure before applying the Predicate
.
You must place the label after a caption in order to for label
to store the table's number, not the chapter's number.
\begin{table} \begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |} -- cut -- \end{tabular} \caption{My table} \label{table:kysymys} \end{table} Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...
Having a map doesn't look good at all with a large amount of components. I'm actually surprised that no one has suggested something like this:
var componentName = "StringThatContainsComponentName";
const importedComponentModule = require("path/to/component/" + componentName).default;
return React.createElement(importedComponentModule);
This one has really helped me when I needed to render a pretty large amount of components loaded in a form of json array.
Regarding:
var button = document.getElementById(/* Button client id */);
button.click();
It should be like:
var button = document.getElementById('<%=formID.ClientID%>');
Where formID is the ASP.NET control ID in the .aspx file.
You can do it like this:
Table::select('name','surname')->where('id', 1)->get();
For a simple state machine just use a switch statement and an enum type for your state. Do your transitions inside the switch statement based on your input. In a real program you would obviously change the "if(input)" to check for your transition points. Hope this helps.
typedef enum
{
STATE_1 = 0,
STATE_2,
STATE_3
} my_state_t;
my_state_t state = STATE_1;
void foo(char input)
{
...
switch(state)
{
case STATE_1:
if(input)
state = STATE_2;
break;
case STATE_2:
if(input)
state = STATE_3;
else
state = STATE_1;
break;
case STATE_3:
...
break;
}
...
}
I tweaked the accepted answer to perform the operation for multiple dataframes on different suffix
parameters using reduce
and i guess it can be extended to different on
parameters as well.
from functools import reduce
dfs_with_suffixes = [(df2,suffix2), (df3,suffix3),
(df4,suffix4)]
merge_one = lambda x,y,sfx:pd.merge(x,y,on=['col1','col2'..], suffixes=sfx)
merged = reduce(lambda left,right:merge_one(left,*right), dfs_with_suffixes, df1)
You can use this command line to identify the current container ID (tested with docker 1.9).
awk -F"-|/." '/1:/ {print $3}' /proc/self/cgroup
Then, a little request to Docker API (you can share /var/run/docker.sock) to retrieve all informations.
To check the emptiness of a queryset:
if orgs.exists():
# Do something
or you can check for a the first item in a queryset, if it doesn't exist it will return None
:
if orgs.first():
# Do something
I recommend you use:
var returnedData = JSON.parse(response);
to convert the JSON string (if it is just text) to a JavaScript object.
like this:
/\<word\>
\<
means beginning of a word, and \>
means the end of a word,
Adding @Roe's comment:
VIM provides a shortcut for this. If you already have word on screen and you want to find other instances of it, you can put the cursor on the word and press '*'
to search forward in the file or '#'
to search backwards.
EDIT Ignore this answer. There are now better answers. See the comments. Use + theme_classic()
EDIT
This is a better version. The bug mentioned below in the original post remains (I think). But the axis line is drawn under the panel. Therefore, remove both the panel.border
and panel.background
to see the axis lines.
library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
ggplot(df, aes(x = a, y = b)) + geom_point() +
theme_bw() +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
Original post
This gets close. There was a bug with axis.line
not working on the y-axis (see here), that appears not to be fixed yet. Therefore, after removing the panel border, the y-axis has to be drawn in separately using geom_vline
.
library(ggplot2)
library(grid)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
p = ggplot(df, aes(x = a, y = b)) + geom_point() +
scale_y_continuous(expand = c(0,0)) +
scale_x_continuous(expand = c(0,0)) +
theme_bw() +
opts(axis.line = theme_segment(colour = "black"),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
panel.border = theme_blank()) +
geom_vline(xintercept = 0)
p
The extreme points are clipped, but the clipping can be undone using code by baptiste.
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)
Or use limits
to move the boundaries of the panel.
ggplot(df, aes(x = a, y = b)) + geom_point() +
xlim(0,22) + ylim(.95, 2.1) +
scale_x_continuous(expand = c(0,0), limits = c(0,22)) +
scale_y_continuous(expand = c(0,0), limits = c(.95, 2.2)) +
theme_bw() +
opts(axis.line = theme_segment(colour = "black"),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
panel.border = theme_blank()) +
geom_vline(xintercept = 0)
GNU grep can also support positive & negative look-ahead & look-back: For your case, the command would be:
echo "Here is a string" | grep -o -P '(?<=Here).*(?=string)'
If there are multiple occurrences of Here
and string
, you can choose whether you want to match from the first Here
and last string
or match them individually. In terms of regex, it is called as greedy match (first case) or non-greedy match (second case)
$ echo 'Here is a string, and Here is another string.' | grep -oP '(?<=Here).*(?=string)' # Greedy match
is a string, and Here is another
$ echo 'Here is a string, and Here is another string.' | grep -oP '(?<=Here).*?(?=string)' # Non-greedy match (Notice the '?' after '*' in .*)
is a
is another
First you should understand how factorial works.
Lets take 4! as an example.
4! = 4 * 3 * 2 * 1 = 24
Let us simulate the code using the example above:
int fact(int n)
{
int result;
if(n==0 || n==1)
return 1;
result = fact(n-1) * n;
return result;
}
In most programming language, we have what we call function stack
. It is just like a deck of cards, where each card is placed above the other--and each card may be thought of as a function So, passing on method fact
:
Stack level 1: fact(4) // n = 4 and is not equal to 1. So we call fact(n-1)*n
Stack level 2: fact(3)
Stack level 3: fact(2)
Stack level 4: fact(1)
// now, n = 1. so we return 1 from this function.
returning values...
Stack level 3: 2 * fact(1) = 2 * 1 = 2
Stack level 2: 3 * fact(2) = 3 * 2 = 6
Stack level 1: 4 * fact(3) = 4 * 6 = 24
so we got 24.
Take note of these lines:
result = fact(n-1) * n;
return result;
or simply:
return fact(n-1) * n;
This calls the function itself. Using 4 as an example,
In sequence according to function stacks..
return fact(3) * 4;
return fact(2) * 3 * 4
return fact(1) * 2 * 3 * 4
Substituting results...
return 1 * 2 * 3 * 4 = return 24
I hope you get the point.
select 1 from table
will return a column of 1's for every row in the table. You could use it with a where statement to check whether you have an entry for a given key, as in:
if exists(select 1 from table where some_column = 'some_value')
What your friend was probably saying is instead of making bulk selects with select * from table, you should specify the columns that you need precisely, for two reasons:
1) performance & you might retrieve more data than you actually need.
2) the query's user may rely on the order of columns. If your table gets updated, the client will receive columns in a different order than expected.
I think this example will help you in understanding this more simply.
Path differences in Windows
Windows absolute path C:\Windows\calc.exe
Windows non absolute path (relative path) calc.exe
In the above example, the absolute path contains the full path to the file and not just the file as seen in the non absolute path. In this example, if you were in a directory that did not contain "calc.exe" you would get an error message. However, when using an absolute path you can be in any directory and the computer would know where to open the "calc.exe" file.
Path differences in Linux
Linux absolute path /home/users/c/computerhope/public_html/cgi-bin
Linux non absolute path (relative path) /public_html/cgi-bin
In these example, the absolute path contains the full path to the cgi-bin directory on that computer. How to find the absolute path of a file in Linux Since most users do not want to see the full path as their prompt, by default the prompt is relative to their personal directory as shown above. To find the full absolute path of the current directory use the pwd command.
It is a best practice to use relative file paths (if possible).
When using relative file paths, your web pages will not be bound to your current base URL. All links will work on your own computer (localhost) as well as on your current public domain and your future public domains.
After importing stored procedure, you can create object of stored procedure pass the parameter like function
using (var entity = new FunctionsContext())
{
var DBdata = entity.GetFunctionByID(5).ToList<Functions>();
}
or you can also use SqlQuery
using (var entity = new FunctionsContext())
{
var Parameter = new SqlParameter {
ParameterName = "FunctionId",
Value = 5
};
var DBdata = entity.Database.SqlQuery<Course>("exec GetFunctionByID @FunctionId ", Parameter).ToList<Functions>();
}
By using priority paramenter for @Test we can control the order of test execution.
I've written a log file monitor before, and I found that the impact on system performance of polling the attributes of a single file, a few times a second, is actually very small.
Java 7, as part of NIO.2 has added the WatchService API
The WatchService API is designed for applications that need to be notified about file change events.
For this specific conversion we can also use a format string.
$new = vsprintf('%3$s-%2$s-%1$s', explode('-', $old));
Obviously this won't work for many other date format conversions, but since we're just rearranging substrings in this case, this is another possible way to do it.
The solution of @JarekTkaczyk it is exactly what I was looking for. The only thing I miss is how to do it when you are using
DB::table()
queries. In this case, this is how I do it:
$other = DB::table( DB::raw("({$sub->toSql()}) as sub") )->select(
'something',
DB::raw('sum( qty ) as qty'),
'foo',
'bar'
);
$other->mergeBindings( $sub );
$other->groupBy('something');
$other->groupBy('foo');
$other->groupBy('bar');
print $other->toSql();
$other->get();
Special atention how to make the mergeBindings
without using the getQuery()
method
David Walsh has a nice solution for this. Here is my take on this, combining his solution with what has been discovered on this thread as well.
https://davidwalsh.name/global-variables-javascript
x = {};
var iframe = document.createElement('iframe');
iframe.onload = function() {
var standardGlobals = Object.keys(iframe.contentWindow);
for(var b in window) {
const prop = window[b];
if(window.hasOwnProperty(b) && prop && !prop.toString().includes('native code') && !standardGlobals.includes(b)) {
x[b] = prop;
}
}
console.log(x)
};
iframe.src = 'about:blank';
document.body.appendChild(iframe);
x
now has only the globals.
First include the header corresponding to the .cpp... in other words, source1.cpp
should include source1.h
before including anything else. The only exception I can think of is when using MSVC with pre-compiled headers in which case, you are forced to include stdafx.h
before anything else.
Reasoning: Including the source1.h
before any other files ensures that it can stand alone without it's dependencies. If source1.h
takes on a dependency on a later date, the compiler will immediately alert you to add the required forward declarations to source1.h
. This in turn ensures that headers can be included in any order by their dependants.
Example:
source1.h
class Class1 {
Class2 c2; // a dependency which has not been forward declared
};
source1.cpp
#include "source1.h" // now compiler will alert you saying that Class2 is undefined
// so you can forward declare Class2 within source1.h
...
MSVC users: I strongly recommend using pre-compiled headers. So, move all #include
directives for standard headers (and other headers which are never going to change) to stdafx.h
.
Use this line of code in your css
border: 1px solid #000 !important;
or if you want border only in left and right side of container then use:
border-right: 1px solid #000 !important;
border-left: 1px solid #000 !important;
Little addition. You can use boost::function
, to create functors from functions and methods, like this:
class Foo
{
public:
void operator () (int i) { printf("Foo %d", i); }
};
void Bar(int i) { printf("Bar %d", i); }
Foo foo;
boost::function<void (int)> f(foo);//wrap functor
f(1);//prints "Foo 1"
boost::function<void (int)> b(&Bar);//wrap normal function
b(1);//prints "Bar 1"
and you can use boost::bind to add state to this functor
boost::function<void ()> f1 = boost::bind(foo, 2);
f1();//no more argument, function argument stored in f1
//and this print "Foo 2" (:
//and normal function
boost::function<void ()> b1 = boost::bind(&Bar, 2);
b1();// print "Bar 2"
and most useful, with boost::bind and boost::function you can create functor from class method, actually this is a delegate:
class SomeClass
{
std::string state_;
public:
SomeClass(const char* s) : state_(s) {}
void method( std::string param )
{
std::cout << state_ << param << std::endl;
}
};
SomeClass *inst = new SomeClass("Hi, i am ");
boost::function< void (std::string) > callback;
callback = boost::bind(&SomeClass::method, inst, _1);//create delegate
//_1 is a placeholder it holds plase for parameter
callback("useless");//prints "Hi, i am useless"
You can create list or vector of functors
std::list< boost::function<void (EventArg e)> > events;
//add some events
....
//call them
std::for_each(
events.begin(), events.end(),
boost::bind( boost::apply<void>(), _1, e));
There is one problem with all this stuff, compiler error messages is not human readable :)
You should use profiles.
<profiles>
<profile>
<id>otherOutputDir</id>
<build>
<directory>yourDirectory</directory>
</build>
</profile>
</profiles>
And start maven with your profile
mvn compile -PotherOutputDir
If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :
<properties>
<buildDirectory>${project.basedir}/target</buildDirectory>
</properties>
<build>
<directory>${buildDirectory}</directory>
</build>
And compile like this :
mvn compile -DbuildDirectory=test
That's because you can't change the target directory by using -Dproject.build.directory
When using Windows, the comparison is cut short: memcache
appears to be the only client available.
Sharing my solution here, based on Chris' answer. Hope it can help others.
I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:
export class Settings extends React.PureComponent {
render() {
const loading = (<div>I'm Loading</div>);
let content = [];
let pushMessages = null;
let emailMessages = null;
if (this.props.pushPreferences) {
pushMessages = (<div>Push Content Here</div>);
}
if (this.props.emailPreferences) {
emailMessages = (<div>Email Content Here</div>);
}
// Push the components in the order I want
if (emailMessages) content.push(emailMessages);
if (pushMessages) content.push(pushMessages);
return (
<div>
{content.length ? content : loading}
</div>
)
}
Now, I do realize I could also just put {pushMessages}
and {emailMessages}
directly in my return()
below, but assuming I had even more conditional content, my return()
would just look cluttered.
try this code, it will work for all version of URLs like
RewriteCond %{HTTPS} off
RewriteCond %{HTTPS_HOST} !^www.website.com$ [NC]
RewriteRule ^(.*)$ https://www.website.com/$1 [L,R=301]
You can also use DataTable - you can define then the number of columns and their types and then add rows http://www.dotnetperls.com/datatable
One way to do it is to use bullet points, which allows you specify multiple levels of indentation. Bullet points are inserted using multiples of two spaces, star, another space Eg.:
this is a normal line of text
* this is the first level of bullet points, made up of <space><space>*<space>
* this is more indented, composed of <space><space><space><space>*<space>
This method has the great advantage that it also makes sense when you view the raw text.
If you care about not seeing the bullet points themselves, you should (depending on where you're using markdown) to be able to add li {list-style-type: none;}
to the css for the whole mark down area.
You would not know your container is behind without running docker pull. Then you'd need to rebuild or recompose your image.
docker pull image:tag
docker-compose -f docker-compose.yml -f production.yml up -d --build
The commands can be put in a script along with anything else necessary to complete the upgrade, although a proper container would not need anything additional.
This is my simplified example of how to run RAW SELECT, get result and access the values.
$res = DB::select('
select count(id) as c
from prices p
where p.type in (2,3)
');
if ($res[0]->c > 10)
{
throw new Exception('WOW');
}
If you want only run sql script with no return resutl use this
DB::statement('ALTER TABLE products MODIFY COLUMN physical tinyint(1) AFTER points;');
Tested in laravel 5.1
I was using a playbook like this to test my roles locally:
---
- hosts: localhost
roles:
- role: .
but this stopped working with Ansible v2.2.
I debugged the aforementioned solution of
---
- hosts: all
tasks:
- name: Find out playbooks path
shell: pwd
register: playbook_path_output
- debug: var=playbook_path_output.stdout
and it produced my home directory and not the "current working directory"
I settled with
---
- hosts: all
roles:
- role: '{{playbook_dir}}'
per the solution above.
Use the -S switch
g++ -S main.cpp
or also with gcc
gcc -S main.c
Also see this
If you are running on Redhat, do following
Stop Jenkins
$sudo service jenkins stop
change port number in /etc/sysconfig/jenkins
like i did for port 8081
JENKINS_PORT="8081"
start Jenkins again
$sudo service jenkins start
If you happen to be using the Bootstrap CSS library, you can use the responsive embed classes that it provides:
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/zpOULjyy-n8?rel=0" allowfullscreen></iframe>
</div>
Several different aspect ratios are supported, see the documentation.
One more way to do this is:
git config remote.origin.url https://github.com/abc/abc.git
To see the existing URL just do:
git config remote.origin.url
As a one-liner function:
def is_leap_year(year):
"""Determine whether a year is a leap year."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
It's similar to the Mark's answer, but short circuits at the first test (note the parenthesis).
Alternatively, you can use the standard library's calendar.isleap
, which has exactly the same implementation:
from calendar import isleap
print(isleap(1900))
The original answer by Adam Batkin will lead you to a solution, but if you redeploy your webapp (without restarting your web container), you should run into the following error:
java.lang.UnsatisfiedLinkError: Native Library "foo" already loaded in another classloader
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1715)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1646)
at java.lang.Runtime.load0(Runtime.java:787)
at java.lang.System.load(System.java:1022)
This happens because the ClassLoader that originally loaded your DLL still references this DLL. However, your webapp is now running with a new ClassLoader, and because the same JVM is running and a JVM won't allow 2 references to the same DLL, you can't reload it. Thus, your webapp can't access the existing DLL and can't load a new one. So.... you're stuck.
Tomcat's ClassLoader documentation outlines why your reloaded webapp runs in a new isolated ClassLoader and how you can work around this limitation (at a very high level).
The solution is to extend Adam Batkin's solution a little:
package awesome;
public class Foo {
static {
System.loadLibrary('foo');
}
// required to work with JDK 6 and JDK 7
public static void main(String[] args) {
}
}
Then placing a jar containing JUST this compiled class into the TOMCAT_HOME/lib folder.
Now, within your webapp, you just have to force Tomcat to reference this class, which can be done as simply as this:
Class.forName("awesome.Foo");
Now your DLL should be loaded in the common classloader, and can be referenced from your webapp even after being redeployed.
Make sense?
A working reference copy can be found on google code, static-dll-bootstrapper .
Please check this:
import webbrowser
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
webbrowser.get(chrome_path).open('http://docs.python.org/')
The complete first argument of exec
is being interpreted as the executable. Use
p = rt.exec(new String[] {"winrar.exe", "x", "h:\\myjar.jar", "*.*", "h:\\new" }
null,
dir);
The only case where you may want such a function is an UPDATE query which will alter your table to store Firstname and Lastname into separate fields.
Database design must follow certain rules, and Database Normalization is among most important ones
Maybe (from git commit
man page):
git commit --no-verify
-n
--no-verify
This option bypasses the pre-commit and commit-msg hooks. See also githooks(5).
As commented by Blaise, -n
can have a different role for certain commands.
For instance, git push -n
is actually a dry-run push.
Only git push --no-verify
would skip the hook.
Note: Git 2.14.x/2.15 improves the --no-verify behavior:
See commit 680ee55 (14 Aug 2017) by Kevin Willford (``).
(Merged by Junio C Hamano -- gitster
-- in commit c3e034f, 23 Aug 2017)
commit
: skip discarding the index if there is nopre-commit
hook"
git commit
" used to discard the index and re-read from the filesystem just in case thepre-commit
hook has updated it in the middle; this has been optimized out when we know we do not run thepre-commit
hook.
Davi Lima points out in the comments the git cherry-pick
does not support --no-verify.
So if a cherry-pick triggers a pre-commit hook, you might, as in this blog post, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.
The same process would be necessary in case of a git rebase --continue
, after a merge conflict resolution.
Here is another ES6 way of doing it with O(n) complexity
const result = Object.entries(
['pear', 'apple', 'orange', 'apple'].reduce((previous, current) => {
if (previous[current] === undefined) previous[current] = 1;
else previous[current]++;
return previous;
}, {})).reduce((previous, current) => (current[1] >= previous[1] ? current : previous))[0];
console.log("Max value : " + result);
I wanted to change default java version form 1.6* to 1.7*. I tried the following steps and it worked for me:
ln -s /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/bin/java java
java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)
In case this happens to anyone else who tried both alphazero and Paul's method and still didn't work.
For me, eclipse somehow 'cached' the compile errors even after doing a Project > Clean...
I had to uncheck Project > Build Automatically, then do a Project > Clean, and then build again.
Also, when in doubt, try restarting Eclipse. This can fix a lot of awkward, unexplainable errors.
I have a page (form) that dynamically generates checkbox so these answers have been a great help. My solution is very similar to many here but I can't help thinking it is easier to implement.
First I put a hidden input box in line with my checkbox , i.e.
<td><input class = "chkhide" type="hidden" name="delete_milestone[]" value="off"/><input type="checkbox" name="delete_milestone[]" class="chk_milestone" ></td>
Now if all the checkboxes
are un-selected then values returned by the hidden field will all be off.
For example, here with five dynamically inserted checkboxes, the form POSTS
the following values:
'delete_milestone' =>
array (size=7)
0 => string 'off' (length=3)
1 => string 'off' (length=3)
2 => string 'off' (length=3)
3 => string 'on' (length=2)
4 => string 'off' (length=3)
5 => string 'on' (length=2)
6 => string 'off' (length=3)
This shows that only the 3rd and 4th checkboxes are on
or checked
.
In essence the dummy or hidden input field just indicates that everything is off unless there is an "on" below the off index, which then gives you the index you need without a single line of client side code.
.
you can do this by using just one line code..
<h1><img src="img/logo.png" alt="logo"/>My website name</h1>
When the C# 5 CTP was introduced, you certainly could mark Main with async
... although it was generally not a good idea to do so. I believe this was changed by the release of VS 2013 to become an error.
Unless you've started any other foreground threads, your program will exit when Main
completes, even if it's started some background work.
What are you really trying to do? Note that your GetList()
method really doesn't need to be async at the moment - it's adding an extra layer for no real reason. It's logically equivalent to (but more complicated than):
public Task<List<TvChannel>> GetList()
{
return new GetPrograms().DownloadTvChannels();
}
Don't use jquery...use plain javascript
var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var b = a.splice(0,10);
//a is now [11,12,13,14,15];
//b is now [1,2,3,4,5,6,7,8,9,10];
You could loop this to get the behavior you want.
var a = YOUR_ARRAY;
while(a.length) {
console.log(a.splice(0,10));
}
This would give you 10 elements at a time...if you have say 15 elements, you would get 1-10, the 11-15 as you wanted.
You could also check if the id element is used by doing so:
if(typeof $(.div).attr('id') == undefined){
//element has no id
} else {
//element has id selector
}
I use this method for global dataTables and specific ordered dataTables
Here you'll find your answer:
Using Git how do I find changes between local and remote
For the lazy:
- Use "git log origin..HEAD"
- Use "git fetch" followed by "git log HEAD..origin". You can cherry-pick individual commits using the listed commit ids.
The above assumes, of course, that "origin" is the name of your remote tracking branch (which it is if you've used clone with default options).
Dont know whether I should put this as answer or not...
I used @Zeeshan0026's solution to draw the path...and the problem was that if I draw path once, and then I do try to draw path once again, both two paths show and this continues...paths showing even when markers were deleted... while, ideally, old paths' shouldn't be there once new path is drawn / markers are deleted..
going through some other question over SO, I had the following solution
I add the following function in Zeeshan's class
public void clearRoute(){
for(Polyline line1 : polylines)
{
line1.remove();
}
polylines.clear();
}
in my map activity, before drawing the path, I called this function.. example usage as per my app is
private Route rt;
rt.clearRoute();
if (src == null) {
Toast.makeText(getApplicationContext(), "Please select your Source", Toast.LENGTH_LONG).show();
}else if (Destination == null) {
Toast.makeText(getApplicationContext(), "Please select your Destination", Toast.LENGTH_LONG).show();
}else if (src.equals(Destination)) {
Toast.makeText(getApplicationContext(), "Source and Destinatin can not be the same..", Toast.LENGTH_LONG).show();
}else{
rt.drawRoute(mMap, MapsMainActivity.this, src,
Destination, false, "en");
}
you can use rt.clearRoute();
as per your requirements..
Hoping that it will save a few minutes of someone else and will help some beginner in solving this issue..
Complete Class Code
see on github
Edit: here is part of code from mainactivity..
case R.id.mkrbtn_set_dest:
Destination = selmarker.getPosition();
destmarker = selmarker;
desShape = createRouteCircle(Destination, false);
if (src == null) {
Toast.makeText(getApplicationContext(),
"Please select your Source first...",
Toast.LENGTH_LONG).show();
} else if (src.equals(Destination)) {
Toast.makeText(getApplicationContext(),
"Source and Destinatin can not be the same..",
Toast.LENGTH_LONG).show();
} else {
if (isNetworkAvailable()) {
rt.drawRoute(mMap, MapsMainActivity.this, src,
Destination, false, "en");
src = null;
Destination = null;
} else {
Toast.makeText(
getApplicationContext(),
"Internet Connection seems to be OFFLINE...!",
Toast.LENGTH_LONG).show();
}
}
break;
Edit 2 as per comments
usage :
//variables as data members
GoogleMap mMap;
private Route rt;
static LatLng src;
static LatLng Destination;
//MapsMainActivity is my activity
//false for interim stops for traffic, google
// en language for html description returned
rt.drawRoute(mMap, MapsMainActivity.this, src,
Destination, false, "en");
Goto my blog : retrofit with kotlin
the link below explains everything step by step.
http://loopj.com/android-async-http/
Here are sample apps:
Create a class :
public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Call Method :
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa@123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Please grant internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
you can add compile 'com.loopj.android:android-async-http:1.4.9'
for Header[]
and compile 'org.json:json:20160212'
for JSONObject
in build.gradle file if required.
Before implementying any of this, please see Scott Arciszewski's answer.
I want you to be very careful with what I'm about to share as I have little to no security knowledge (There's a high chance that I'm misusing the API below), so I'd be more than welcome to update this answer with the help of the community.
As @richardtallent mentioned in his answer, there's support for the Web Crypto API, so this example uses the standard. As of this writing, there's a 95.88% of global browser support.
I'm going to be sharing an example using the Web Crypto API
Before we proceed, please note (Quoting from MDN):
This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle.
Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right and are generally the domain of specialist security experts.
Errors in security system design and implementation can make the security of the system completely ineffective.
If you're not sure you know what you are doing, you probably shouldn't be using this API.
I respect security a lot, and I even bolded additional parts from MDN... You've been warned
Now, to the actual example...
Found here: https://jsfiddle.net/superjose/rm4e0gqa/5/
Note the use of await
keywords. Use it inside an async
function or use .then()
and .catch()
.
// https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey
// https://developer.mozilla.org/en-US/docs/Web/API/RsaHashedKeyGenParams
// https://github.com/diafygi/webcrypto-examples#rsa-oaep---generatekey
const stringToEncrypt = 'https://localhost:3001';
// https://github.com/diafygi/webcrypto-examples#rsa-oaep---generatekey
// The resultant publicKey will be used to encrypt
// and the privateKey will be used to decrypt.
// Note: This will generate new keys each time, you must store both of them in order for
// you to keep encrypting and decrypting.
//
// I warn you that storing them in the localStorage may be a bad idea, and it gets out of the scope
// of this post.
const key = await crypto.subtle.generateKey({
name: 'RSA-OAEP',
modulusLength: 4096,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {name: 'SHA-512'},
}, true,
// This depends a lot on the algorithm used
// Go to https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto
// and scroll down to see the table. Since we're using RSA-OAEP we have encrypt and decrypt available
['encrypt', 'decrypt']);
// key will yield a key.publicKey and key.privateKey property.
const encryptedUri = await crypto.subtle.encrypt({
name: 'RSA-OAEP'
}, key.publicKey, stringToArrayBuffer(stringToEncrypt))
console.log('The encrypted string is', encryptedUri);
const msg = await crypto.subtle.decrypt({
name: 'RSA-OAEP',
}, key.privateKey, encryptedUri);
console.log(`Derypted Uri is ${arrayBufferToString(msg)}`)
private arrayBufferToString(buff: ArrayBuffer) {
return String.fromCharCode.apply(null, new Uint16Array(buff) as unknown as number[]);
}
private stringToArrayBuffer(str: string) {
const buff = new ArrayBuffer(str.length*2) // Because there are 2 bytes for each char.
const buffView = new Uint16Array(buff);
for(let i = 0, strLen = str.length; i < strLen; i++) {
buffView[i] = str.charCodeAt(i);
}
return buff;
}
You can find more examples here (I'm not the owner): // https://github.com/diafygi/webcrypto-examples