use this class to compress image
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.net.Uri
import android.os.Environment
import java.io.*
class ImageFile(val uri: Uri, name: String) {
val filename: String
init {
val file = File(Environment.getExternalStorageDirectory().toString() + "/Documents")
if (!file.exists()) {
file.mkdirs()
}
val fileNoMedia = File(file.absolutePath + "/.nomedia")
if (!fileNoMedia.exists())
fileNoMedia.createNewFile()
if (name.toLowerCase().endsWith(".pdf")) {
filename = file.absolutePath + "/" + System.currentTimeMillis() + ".pdf"
} else {
filename = file.absolutePath + "/" + System.currentTimeMillis() + ".jpg"
}
}
@Throws(IOException::class)
fun copyFileStream(context: Context, uri: Uri): String {
if (filename.endsWith(".pdf") || filename.endsWith(".PDF")) {
var ins: InputStream? = null
var os: OutputStream? = null
try {
ins = context.getContentResolver().openInputStream(uri)
os = FileOutputStream(filename)
val buffer = ByteArray(1024)
var length: Int = ins.read(buffer)
while (length > 0) {
os.write(buffer, 0, length);
length = ins.read(buffer)
}
} catch (e: Exception) {
e.printStackTrace();
} finally {
ins?.close()
os?.close()
}
} else {
var ins: InputStream? = null
var os: OutputStream? = null
try {
ins = context.getContentResolver().openInputStream(uri)
var scaledBitmap: Bitmap? = null
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
var bmp = BitmapFactory.decodeStream(ins, null, options)
var actualHeight = options.outHeight
var actualWidth = options.outWidth
// max Height and width values of the compressed image is taken as 816x612
val maxHeight = 816.0f
val maxWidth = 612.0f
var imgRatio = (actualWidth / actualHeight).toFloat()
val maxRatio = maxWidth / maxHeight
// width and height values are set maintaining the aspect ratio of the image
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight
actualWidth = (imgRatio * actualWidth).toInt()
actualHeight = maxHeight.toInt()
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth
actualHeight = (imgRatio * actualHeight).toInt()
actualWidth = maxWidth.toInt()
} else {
actualHeight = maxHeight.toInt()
actualWidth = maxWidth.toInt()
}
}
// setting inSampleSize value allows to load a scaled down version of the original image
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight)
// inJustDecodeBounds set to false to load the actual bitmap
options.inJustDecodeBounds = false
// this options allow android to claim the bitmap memory if it runs low on memory
options.inPurgeable = true
options.inInputShareable = true
options.inTempStorage = ByteArray(16 * 1024)
try {
// load the bitmap from its path
ins.close()
ins = context.getContentResolver().openInputStream(uri)
bmp = BitmapFactory.decodeStream(ins, null, options)
} catch (exception: OutOfMemoryError) {
exception.printStackTrace()
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888)
} catch (exception: OutOfMemoryError) {
exception.printStackTrace()
}
val ratioX = actualWidth / options.outWidth.toFloat()
val ratioY = actualHeight / options.outHeight.toFloat()
val middleX = actualWidth / 2.0f
val middleY = actualHeight / 2.0f
val scaleMatrix = Matrix()
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY)
val canvas = Canvas(scaledBitmap!!)
canvas.matrix = scaleMatrix
canvas.drawBitmap(bmp, middleX - bmp.width / 2, middleY - bmp.height / 2, Paint(Paint.FILTER_BITMAP_FLAG))
os = FileOutputStream(filename)
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, os)
val buffer = ByteArray(1024)
var length: Int = ins.read(buffer)
while (length > 0) {
os.write(buffer, 0, length);
length = ins.read(buffer)
}
} catch (e: Exception) {
e.printStackTrace();
} finally {
ins?.close()
os?.close()
}
}
return filename
}
fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
val height = options.outHeight
val width = options.outWidth
var inSampleSize = 1
if (height > reqHeight || width > reqWidth) {
val heightRatio = Math.round(height.toFloat() / reqHeight.toFloat())
val widthRatio = Math.round(width.toFloat() / reqWidth.toFloat())
inSampleSize = if (heightRatio < widthRatio) heightRatio else widthRatio
}
val totalPixels = (width * height).toFloat()
val totalReqPixelsCap = (reqWidth * reqHeight * 2).toFloat()
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++
}
return inSampleSize
}
}
https://lalitjadav007.blogspot.in/2017/08/compress-image-in-android.html
Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Margin="0,0,0,0" Background="Transparent"
BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header" Margin="12,2,12,2"
RecognizesAccessKey="True">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="100" />
<Setter TargetName="Border" Property="Background" Value="Red" />
<Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
<Setter Property="Foreground" Value="DarkGray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
You can update the value like following
auto itr = m.find('ch');
if (itr != m.end()){
(*itr).second = 98;
}
Run:
mysqldump -u root -p your_target_DB --compatible=mssql > MSSQL_Compatible_Data.sql
Do you want to see a process bar?
pv mysqldump -u root -p your_target_DB --compatible=mssql > MSSQL_Compatible_Data.sql
Try to do following:
Go to your Server
cd rep.git
chmod -R g+ws *
chgrp -R git *
git config core.sharedRepository true
Then go to your working copy(local repository) and repack it by git repack master
Works perfectly to me.
Just right click on a conflicting file and add it to the index after resolving conflicts.
The standard approach is to use sprintf(buffer, "%lu", value);
to write a string rep of value
to buffer
. However, overflow is a potential problem, as sprintf
will happily (and unknowingly) write over the end of your buffer.
This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.
This site discusses this and related problems at some length.
Some libraries offer snprintf
as an alternative which lets you specify a maximum buffer size.
Try this one -
WHERE DateDropped = 0
AND (
(ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0)
OR
(ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)
)
With Guava:
final Splitter splitter = Splitter.on("-").trimResults();
assertEquals("Günnewig Uebachs", Iterables.getLast(splitter.split(one)));
assertEquals("Madison", Iterables.getLast(splitter.split(two)));
If you uncheck the ADB Integration, you cannot use the debug any more.You may just restart the adb server, run
$adb kill-server
$adb start-server
in Terminal to restart the adb server without restarting the Android Studio. Then the emulator shows up.
Using detach is magnitudes faster than any of the other answers here:
$('#mytable').find('tbody').detach();
Don't forget to put the tbody element back into the table since detach removed it:
$('#mytable').append($('<tbody>'));
Also note that when talking efficiency $(target).find(child)
syntax is faster than $(target > child)
. Why? Sizzle!
Elapsed Time to Empty 3,161 Table Rows
Using the Detach() method (as shown in my example above):
Using the empty() method:
Your problem are the cr (carriage return)
http://jsfiddle.net/NT9KB/210/
you can use:
document.getElementById("img").src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
ECMA Script 6 Version
If you are in an environment which supports ECMA Script 6's Set
, then you can use Array.prototype.some
and a Set
object, like this
let seen = new Set();
var hasDuplicates = values.some(function(currentObject) {
return seen.size === seen.add(currentObject.name).size;
});
Here, we insert each and every object's name
into the Set
and we check if the size
before and after adding are the same. This works because Set.size
returns a number based on unique data (set only adds entries if the data is unique). If/when you have duplicate names, the size won't increase (because the data won't be unique) which means that we would have already seen the current name and it will return true.
ECMA Script 5 Version
If you don't have Set
support, then you can use a normal JavaScript object itself, like this
var seen = {};
var hasDuplicates = values.some(function(currentObject) {
if (seen.hasOwnProperty(currentObject.name)) {
// Current name is already seen
return true;
}
// Current name is being seen for the first time
return (seen[currentObject.name] = false);
});
The same can be written succinctly, like this
var seen = {};
var hasDuplicates = values.some(function (currentObject) {
return seen.hasOwnProperty(currentObject.name)
|| (seen[currentObject.name] = false);
});
Note: In both the cases, we use Array.prototype.some
because it will short-circuit. The moment it gets a truthy value from the function, it will return true
immediately, it will not process rest of the elements.
You don't need remove, just add again.
cordova plugin add https://github.com/apache/cordova-plugin-camera
This is works faster than 0.1 milliseconds.
return (b >> bitNumber) & 1;
Just in case you are like me and the Id Field of the User Entity is an Int or something else other than a string,
using Microsoft.AspNet.Identity;
int userId = User.Identity.GetUserId<int>();
will do the trick
I know you ask how to disable the option, but I figure the end users visual outcome is the same with this solution, although it is probably marginally less resource demanding.
Use the optgroup tag, like so :
<select name="tagging">
<optgroup label="Choose Tagging">
<option value="Option A">Option A</option>
<option value="Option B">Option B</option>
<option value="Option C">Option C</option>
</optgroup>
</select>
For bootstrap 4
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<form class="form-inline my-2 my-lg-0">
<div class="input-group">
<input class="form-control" type="search" placeholder="Search">
<div class="input-group-append">
<div class="input-group-text"><i class="fa fa-search"></i></div>
</div>
</div>
</form>
var message =/*[[${message}]]*/ 'defaultanyvalue';
This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error Goto ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
' do something here
' ******************
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
After pasting the code in ThisOutlookSession
module, you must restart Outlook.
As of python 3.5.2, you can use:
class C(B):
def method(self, arg):
super().method(arg) # This does the same thing as:
# super(C, self).method(arg)
If your subplots also have titles, you may need to adjust the main title size:
plt.suptitle("Main Title", size=16)
std
namespace (where features of the C++ Standard Library, such as string
or vector
, are declared).After you write this instruction, if the compiler sees string
it will know that you may be referring to std::string
, and if it sees vector
, it will know that you may be referring to std::vector
. (Provided that you have included in your compilation unit the header files where they are defined, of course.)
If you don't write it, when the compiler sees string
or vector
it will not know what you are refering to. You will need to explicitly tell it std::string
or std::vector
, and if you don't, you will get a compile error.
Take the solution. I have written this code in an easy format:
const insertWord = (sentence,word,index) => {
var sliceWord = word.slice(""),output = [],join; // Slicing the input word and declaring other variables
var sliceSentence = sentence.slice(""); // Slicing the input sentence into each alphabets
for (var i = 0; i < sliceSentence.length; i++)
{
if (i === index)
{ // checking if index of array === input index
for (var j = 0; j < word.length; j++)
{ // if yes we'll insert the word
output.push(sliceWord[j]); // Condition is true we are inserting the word
}
output.push(" "); // providing a single space at the end of the word
}
output.push(sliceSentence[i]); // pushing the remaining elements present in an array
}
join = output.join(""); // converting an array to string
console.log(join)
return join;
}
The first thing to do is to install the dependencies.
sudo apt-get build-dep python-psycopg2
After that go inside your virtualenv and use
pip install psycopg2-binary
These two commands should solve the problem.
What does copying an object mean? There are a few ways you can copy objects--let's talk about the 2 kinds you're most likely referring to--deep copy and shallow copy.
Since we're in an object-oriented language (or at least are assuming so), let's say you have a piece of memory allocated. Since it's an OO-language, we can easily refer to chunks of memory we allocate because they are usually primitive variables (ints, chars, bytes) or classes we defined that are made of our own types and primitives. So let's say we have a class of Car as follows:
class Car //A very simple class just to demonstrate what these definitions mean.
//It's pseudocode C++/Javaish, I assume strings do not need to be allocated.
{
private String sPrintColor;
private String sModel;
private String sMake;
public changePaint(String newColor)
{
this.sPrintColor = newColor;
}
public Car(String model, String make, String color) //Constructor
{
this.sPrintColor = color;
this.sModel = model;
this.sMake = make;
}
public ~Car() //Destructor
{
//Because we did not create any custom types, we aren't adding more code.
//Anytime your object goes out of scope / program collects garbage / etc. this guy gets called + all other related destructors.
//Since we did not use anything but strings, we have nothing additional to handle.
//The assumption is being made that the 3 strings will be handled by string's destructor and that it is being called automatically--if this were not the case you would need to do it here.
}
public Car(const Car &other) // Copy Constructor
{
this.sPrintColor = other.sPrintColor;
this.sModel = other.sModel;
this.sMake = other.sMake;
}
public Car &operator =(const Car &other) // Assignment Operator
{
if(this != &other)
{
this.sPrintColor = other.sPrintColor;
this.sModel = other.sModel;
this.sMake = other.sMake;
}
return *this;
}
}
A deep copy is if we declare an object and then create a completely separate copy of the object...we end up with 2 objects in 2 completely sets of memory.
Car car1 = new Car("mustang", "ford", "red");
Car car2 = car1; //Call the copy constructor
car2.changePaint("green");
//car2 is now green but car1 is still red.
Now let's do something strange. Let's say car2 is either programmed wrong or purposely meant to share the actual memory that car1 is made of. (It's usually a mistake to do this and in classes is usually the blanket it's discussed under.) Pretend that anytime you ask about car2, you're really resolving a pointer to car1's memory space...that's more or less what a shallow copy is.
//Shallow copy example
//Assume we're in C++ because it's standard behavior is to shallow copy objects if you do not have a constructor written for an operation.
//Now let's assume I do not have any code for the assignment or copy operations like I do above...with those now gone, C++ will use the default.
Car car1 = new Car("ford", "mustang", "red");
Car car2 = car1;
car2.changePaint("green");//car1 is also now green
delete car2;/*I get rid of my car which is also really your car...I told C++ to resolve
the address of where car2 exists and delete the memory...which is also
the memory associated with your car.*/
car1.changePaint("red");/*program will likely crash because this area is
no longer allocated to the program.*/
So regardless of what language you're writing in, be very careful about what you mean when it comes to copying objects because most of the time you want a deep copy.
What are the copy constructor and the copy assignment operator?
I have already used them above. The copy constructor is called when you type code such as Car car2 = car1;
Essentially if you declare a variable and assign it in one line, that's when the copy constructor is called. The assignment operator is what happens when you use an equal sign--car2 = car1;
. Notice car2
isn't declared in the same statement. The two chunks of code you write for these operations are likely very similar. In fact the typical design pattern has another function you call to set everything once you're satisfied the initial copy/assignment is legitimate--if you look at the longhand code I wrote, the functions are nearly identical.
When do I need to declare them myself? If you are not writing code that is to be shared or for production in some manner, you really only need to declare them when you need them. You do need to be aware of what your program language does if you choose to use it 'by accident' and didn't make one--i.e. you get the compiler default. I rarely use copy constructors for instance, but assignment operator overrides are very common. Did you know you can override what addition, subtraction, etc. mean as well?
How can I prevent my objects from being copied? Override all of the ways you're allowed to allocate memory for your object with a private function is a reasonable start. If you really don't want people copying them, you could make it public and alert the programmer by throwing an exception and also not copying the object.
Tray to add text with html value to textarea but it wil not works
value :
$(document).on('click', '.edit_targets_btn', function() {
$('#add_edit_targets').modal('show');
$('#add_edit_targets_form')[0].reset();
$('#targets_modal_title').text('Doel bijwerken');
$('#action').val('targets_update');
$('#targets_submit_btn').val('Opslaan');
$('#callcenter_targets_id').val($(this).attr("callcenter_targets_id"));
$('#targets_title').val($(this).attr("title"));
$("#targets_content").append($(this).attr("content"));
tinymce.init({
selector: '#targets_content',
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
},
browser_spellcheck : true,
plugins: ['advlist autolink lists image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount', 'autoresize'],
toolbar: 'undo redo | formatselect | ' + ' bold italic backcolor | alignleft aligncenter ' + ' alignright alignjustify | bullist numlist outdent indent |' + ' removeformat | image | help',
relative_urls : false,
remove_script_host : false,
image_list: [<?php $stmt = $db->query('SELECT * FROM images WHERE users_id = ' . $get_user_users_id); foreach ($stmt as $row) { ?>{title: '<?=$row['name']?>', value: '<?=$imgurl?>/image_uploads/<?=$row['src']?>'},<?php } ?>],
min_height: 250,
branding: false
});
});
Try this code:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="100dip" tools:context=".MainActivity" > <HorizontalScrollView android:id="@+id/hsv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:fillViewport="true" android:measureAllChildren="false" android:scrollbars="none" > <LinearLayout android:id="@+id/innerLay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal" > <LinearLayout android:id="@+id/asthma_action_plan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/action_plan" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/controlled_medication" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/controlled" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/as_needed_medication" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" android:orientation="horizontal" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/as_needed" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/rescue_medication" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/rescue" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/your_symptoms" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/symptoms" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/your_triggers" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/triggers" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/wheeze_rate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/wheeze_rate" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/peak_flow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/peak_flow" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> </LinearLayout> </HorizontalScrollView> <TextView android:layout_width="fill_parent" android:layout_height="0.2dp" android:layout_alignParentRight="true" android:layout_below="@+id/hsv" android:background="@drawable/ln" /> <LinearLayout android:id="@+id/prev" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:paddingLeft="5dip" android:paddingRight="5dip" android:descendantFocusability="blocksDescendants" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:src="@drawable/prev_arrow" /> </LinearLayout> <LinearLayout android:id="@+id/next" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:paddingLeft="5dip" android:paddingRight="5dip" android:descendantFocusability="blocksDescendants" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:src="@drawable/next_arrow" /> </LinearLayout> </RelativeLayout>
grid_item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/imageView1" android:layout_width="fill_parent" android:layout_height="100dp" android:src="@drawable/ic_launcher" /> </LinearLayout>
MainActivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class MainActivity extends Activity {
LinearLayout asthmaActionPlan, controlledMedication, asNeededMedication,
rescueMedication, yourSymtoms, yourTriggers, wheezeRate, peakFlow;
LayoutParams params;
LinearLayout next, prev;
int viewWidth;
GestureDetector gestureDetector = null;
HorizontalScrollView horizontalScrollView;
ArrayList<LinearLayout> layouts;
int parentLeft, parentRight;
int mWidth;
int currPosition, prevPosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prev = (LinearLayout) findViewById(R.id.prev);
next = (LinearLayout) findViewById(R.id.next);
horizontalScrollView = (HorizontalScrollView) findViewById(R.id.hsv);
gestureDetector = new GestureDetector(new MyGestureDetector());
asthmaActionPlan = (LinearLayout) findViewById(R.id.asthma_action_plan);
controlledMedication = (LinearLayout) findViewById(R.id.controlled_medication);
asNeededMedication = (LinearLayout) findViewById(R.id.as_needed_medication);
rescueMedication = (LinearLayout) findViewById(R.id.rescue_medication);
yourSymtoms = (LinearLayout) findViewById(R.id.your_symptoms);
yourTriggers = (LinearLayout) findViewById(R.id.your_triggers);
wheezeRate = (LinearLayout) findViewById(R.id.wheeze_rate);
peakFlow = (LinearLayout) findViewById(R.id.peak_flow);
Display display = getWindowManager().getDefaultDisplay();
mWidth = display.getWidth(); // deprecated
viewWidth = mWidth / 3;
layouts = new ArrayList<LinearLayout>();
params = new LayoutParams(viewWidth, LayoutParams.WRAP_CONTENT);
asthmaActionPlan.setLayoutParams(params);
controlledMedication.setLayoutParams(params);
asNeededMedication.setLayoutParams(params);
rescueMedication.setLayoutParams(params);
yourSymtoms.setLayoutParams(params);
yourTriggers.setLayoutParams(params);
wheezeRate.setLayoutParams(params);
peakFlow.setLayoutParams(params);
layouts.add(asthmaActionPlan);
layouts.add(controlledMedication);
layouts.add(asNeededMedication);
layouts.add(rescueMedication);
layouts.add(yourSymtoms);
layouts.add(yourTriggers);
layouts.add(wheezeRate);
layouts.add(peakFlow);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Handler().postDelayed(new Runnable() {
public void run() {
horizontalScrollView.smoothScrollTo(
(int) horizontalScrollView.getScrollX()
+ viewWidth,
(int) horizontalScrollView.getScrollY());
}
}, 100L);
}
});
prev.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Handler().postDelayed(new Runnable() {
public void run() {
horizontalScrollView.smoothScrollTo(
(int) horizontalScrollView.getScrollX()
- viewWidth,
(int) horizontalScrollView.getScrollY());
}
}, 100L);
}
});
horizontalScrollView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
});
}
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if (e1.getX() < e2.getX()) {
currPosition = getVisibleViews("left");
} else {
currPosition = getVisibleViews("right");
}
horizontalScrollView.smoothScrollTo(layouts.get(currPosition)
.getLeft(), 0);
return true;
}
}
public int getVisibleViews(String direction) {
Rect hitRect = new Rect();
int position = 0;
int rightCounter = 0;
for (int i = 0; i < layouts.size(); i++) {
if (layouts.get(i).getLocalVisibleRect(hitRect)) {
if (direction.equals("left")) {
position = i;
break;
} else if (direction.equals("right")) {
rightCounter++;
position = i;
if (rightCounter == 2)
break;
}
}
}
return position;
}
}
Let me know if any issue enjoy...
If it comes to a simple object tree to key value list mapping, where key might be a dotted path description from the object's root element to the leaf being inspected, it's rather obvious that a tree conversion to a key-value list is comparable to an object to xml mapping. Each element within an XML document has a defined position and can be converted into a path. Therefore I took XStream as a basic and stable conversion tool and replaced the hierarchical driver and writer parts with an own implementation. XStream also comes with a basic path tracking mechanism which - being combined with the other two - strictly leads to a solution being suitable for the task.
Have you tried adding a configsection
handler to your app.config? e.g.
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
Try:
$result = curl_exec($cURL);
$result = json_decode($result,true);
Now you can access MessageID
from $result['MessageID']
.
As for the database, it's simply using a query like so:
INSERT INTO `tableName`(`Cancelled`,`Queued`,`SMSError`,`SMSIncommingMessage`,`Sent`,`SentDateTime`) VALUES('?','?','?','?','?');
Prepared.
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.
If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.
The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.
So the ultimate difference is:
Note that there is no variable interpolation in Java. Variable interpolation is variable substitution with its value inside a string. An example in Ruby:
#!/usr/bin/ruby
age = 34
name = "William"
puts "#{name} is #{age} years old"
The Ruby interpreter automatically replaces variables with its values inside a string. The fact, that we are going to do interpolation is hinted by sigil characters. In Ruby, it is #{}. In Perl, it could be $, % or @. Java would only print such characters, it would not expand them.
Variable interpolation is not supported in Java. Instead of this, we have string formatting.
package com.zetcode;
public class StringFormatting
{
public static void main(String[] args)
{
int age = 34;
String name = "William";
String output = String.format("%s is %d years old.", name, age);
System.out.println(output);
}
}
In Java, we build a new string using the String.format() method. The outcome is the same, but the methods are different.
See http://en.wikipedia.org/wiki/Variable_interpolation
Edit As of 2019, JEP 326 (Raw String Literals) was withdrawn and superseded by multiple JEPs eventually leading to JEP 378: Text Blocks delivered in Java 15.
A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over the format when desired.
However, still no string interpolation:
Non-Goals: … Text blocks do not directly support string interpolation. Interpolation may be considered in a future JEP. In the meantime, the new instance method
String::formatted
aids in situations where interpolation might be desired.
EDIT: I just realized you want to filter details
, which is an array of hashes. In that case you could do
details.reject { |item| item[:qty].empty? }
The inner data structure itself is not an Array, but a Hash. You can also use select
here, but the block is given the key and value in this case:
irb(main):001:0> h = {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
irb(main):002:0> h.select { |key, value| !value.empty? }
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .",
:qty2=>"1", :price=>"5,204.34 P"}
Or using reject
, which is the inverse of select
(excludes all items for which the given condition holds):
h.reject { |key, value| value.empty? }
Note that this is Ruby 1.9. If you have to maintain compatibility with 1.8, you could do:
Hash[h.reject { |key, value| value.empty? }]
You can go with POSTMAN, an application who makes APIs easy. Fill request fields and then it will generate code for you in different languages. Just click code on the right side and select your prefered language.
I would give a badly written query and ask them how they would go about performance tuning it.
I would ask about set theory. If you don't understand operating in sets, you can't effectively query a relational database.
I would give them some cursor examples and ask how they would rewrite them to make them set-based.
If the job involved imports and exports I would ask questions about SSIS (or other tools involved in doing this used by other datbases). If it involved writing reports, I would want to know that they understand aggregates and grouping (As well as Crystal Reports or SSRS or whatever ereporting tool you use).
I would ask the difference in results between these three queries:
select a.field1
, a.field2
, b.field3
from table1 a
join table2 b
on a.id = b.id
where a.field5 = 'test'
and b.field3 = 1
select a.field1
, a.field2
, b.field3
from table1 a
left join table2 b
on a.id = b.id
where a.field5 = 'test'
and b.field3 = 1
select a.field1
, a.field2
, b.field3
from table1 a
left join table2 b
on a.id = b.id and b.field3 = 1
where a.field5 = 'test'
Gooye if it's possible to use Joda Time in your project then this code works for me:
String dateStr = "2012-10-01T09:45:00.000+02:00";
String customFormat = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
LocalDateTime parsedDate = dtf.parseLocalDateTime(dateStr);
String dateWithCustomFormat = parsedDate.toString(DateTimeFormat.forPattern(customFormat));
System.out.println(dateWithCustomFormat);
here is an example that allows for performing code on each line of the desired areas (pick either from top & bottom of selection, of from selection
Sub doROWSb() 'WORKS for do selected rows SEE FIX ROWS ABOVE (small ver)
Dim E7 As String 'note: workcell E7 shows: BG381
E7 = RANGE("E7") 'see eg below
Dim r As Long 'NOTE: this example has a paste formula(s) down a column(s). WILL REDUCE 10 HOUR DAYS OF PASTING COLUMNS, DOWN TO 3 MINUTES?
Dim c As Long
Dim rCell As RANGE
'Dim LastRow As Long
r = ActiveCell.row
c = ActiveCell.Column 'might not matter if your code affects whole line anyways, still leave as is
Dim FirstRow As Long 'not in use, Delete if only want last row, note: this code already allows for selection as start
Dim LastRow As Long
If 1 Then 'if you are unable to delete rows not needed, just change 2 lines from: If 1, to if 0 (to go from selection last row, to all rows down from selection)
With Selection
'FirstRow = .Rows(1).row 'not used here, Delete if only want last row
LastRow = .Rows(.Rows.Count).row 'find last row in selection
End With
application.CutCopyMode = False 'if not doing any paste op below
Else
LastRow = Cells(Rows.Count, 1).End(xlUp).row 'find last row used in sheet
End If
application.EnableEvents = True 'EVENTS need this?
application.ScreenUpdating = False 'offset-cells(row, col)
'RANGE(E7).Select 'TOP ROW SELECT
RANGE("A1") = vbNullString 'simple macros on-off switch, vb not here: If RANGE("A1").Value > 0 Then
For Each rCell In RANGE(Cells(r, c), Cells(LastRow, c)) 'new
rCell.Select 'make 3 macros for each paste macro below
'your code here:
If 1 Then 'to if 0, if want to paste formulas/formats/all down a column
Selection.EntireRow.Calculate 'calcs all selected rows, even if just selecting 1 cell in each row (might only be doing 1 row aat here, as part of loop)
Else
'dorows() DO ROWS()
'eg's for paste cells down a column, can make 3 separate macros for each: sub alte() altf & altp
Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 'make sub alte () add thisworkbook: application.OnKey "%{e}", "alte"
'Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 'make sub altf () add thisworkbook: application.OnKey "%{f}", "altf"
'Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 'amke sub altp () add thisworkbook: application.OnKey "%{p}", "altp"
End If
Next rCell
'application.CutCopyMode = False 'finished - stop copy mode
'RANGE("A2").Select
goBEEPS (2), (0.25) 'beeps secs
application.EnableEvents = True 'EVENTS
'note: workcell E7 has: SUBSTITUTE(SUBSTITUTE(CELL("address",$BG$369),"$",""),"","")
'other col eg (shows: BG:BG): =SUBSTITUTE(SUBSTITUTE(CELL("address",$BG2),"$",""),ROW(),"")&":"& SUBSTITUTE(SUBSTITUTE(CELL("address",$BG2),"$",""),ROW(),"")
End Sub
'OTHER:
Sub goBEEPSx(b As Long, t As Double) 'beeps secs as: goBEEPS (2), (0.25) OR: goBEEPS(2, 0.25)
Dim dt 'as double 'worked wo as double
Dim x
For b = b To 1 Step -1
Beep
x = Timer
Do
DoEvents
dt = Timer - x
If dt < 0 Then dt = dt + 86400 '86400 no. seconds in a day, in case hit midnight & timer went down to 0
Loop Until dt >= t
Next
End Sub
readlines() reads the entire input file into a list and is not a good performer. Just iterate through the lines in the file. I used 'with' on output.txt so that it is automatically closed when done. That's not needed on 'list1.txt' because it will be closed when the for loop ends.
#!/usr/bin/env python
with open('output.txt', 'a') as f1:
for line in open('list1.txt'):
if 'tests/file/myword' in line:
f1.write(line)
I have an solution for a generic List<> with dynamic binded items.
class PersonalList it's the root element
[XmlRoot("PersonenListe")]
[XmlInclude(typeof(Person))] // include type class Person
public class PersonalList
{
[XmlArray("PersonenArray")]
[XmlArrayItem("PersonObjekt")]
public List<Person> Persons = new List<Person>();
[XmlElement("Listname")]
public string Listname { get; set; }
// Konstruktoren
public PersonalList() { }
public PersonalList(string name)
{
this.Listname = name;
}
public void AddPerson(Person person)
{
Persons.Add(person);
}
}
class Person it's an single list element
[XmlType("Person")] // define Type
[XmlInclude(typeof(SpecialPerson)), XmlInclude(typeof(SuperPerson))]
// include type class SpecialPerson and class SuperPerson
public class Person
{
[XmlAttribute("PersID", DataType = "string")]
public string ID { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("City")]
public string City { get; set; }
[XmlElement("Age")]
public int Age { get; set; }
// Konstruktoren
public Person() { }
public Person(string name, string city, int age, string id)
{
this.Name = name;
this.City = city;
this.Age = age;
this.ID = id;
}
}
class SpecialPerson inherits Person
[XmlType("SpecialPerson")] // define Type
public class SpecialPerson : Person
{
[XmlElement("SpecialInterests")]
public string Interests { get; set; }
public SpecialPerson() { }
public SpecialPerson(string name, string city, int age, string id, string interests)
{
this.Name = name;
this.City = city;
this.Age = age;
this.ID = id;
this.Interests = interests;
}
}
class SuperPerson inherits Person
[XmlType("SuperPerson")] // define Type
public class SuperPerson : Person
{
[XmlArray("Skills")]
[XmlArrayItem("Skill")]
public List<String> Skills { get; set; }
[XmlElement("Alias")]
public string Alias { get; set; }
public SuperPerson()
{
Skills = new List<String>();
}
public SuperPerson(string name, string city, int age, string id, string[] skills, string alias)
{
Skills = new List<String>();
this.Name = name;
this.City = city;
this.Age = age;
this.ID = id;
foreach (string item in skills)
{
this.Skills.Add(item);
}
this.Alias = alias;
}
}
and the main test Source
static void Main(string[] args)
{
PersonalList personen = new PersonalList();
personen.Listname = "Friends";
// normal person
Person normPerson = new Person();
normPerson.ID = "0";
normPerson.Name = "Max Man";
normPerson.City = "Capitol City";
normPerson.Age = 33;
// special person
SpecialPerson specPerson = new SpecialPerson();
specPerson.ID = "1";
specPerson.Name = "Albert Einstein";
specPerson.City = "Ulm";
specPerson.Age = 36;
specPerson.Interests = "Physics";
// super person
SuperPerson supPerson = new SuperPerson();
supPerson.ID = "2";
supPerson.Name = "Superman";
supPerson.Alias = "Clark Kent";
supPerson.City = "Metropolis";
supPerson.Age = int.MaxValue;
supPerson.Skills.Add("fly");
supPerson.Skills.Add("strong");
// Add Persons
personen.AddPerson(normPerson);
personen.AddPerson(specPerson);
personen.AddPerson(supPerson);
// Serialize
Type[] personTypes = { typeof(Person), typeof(SpecialPerson), typeof(SuperPerson) };
XmlSerializer serializer = new XmlSerializer(typeof(PersonalList), personTypes);
FileStream fs = new FileStream("Personenliste.xml", FileMode.Create);
serializer.Serialize(fs, personen);
fs.Close();
personen = null;
// Deserialize
fs = new FileStream("Personenliste.xml", FileMode.Open);
personen = (PersonalList)serializer.Deserialize(fs);
serializer.Serialize(Console.Out, personen);
Console.ReadLine();
}
Important is the definition and includes of the diffrent types.
Various browsers (mis)handle this in various ways. Using title (an old IE 'standard') isn't particularly appropriate, since the title attribute is a mouseover effect. The jQuery solution above (Alexis) seems on the right track, but I don't think the 'error' occurs at a point where it could be caught. I've had success by replacing at the src with itself, and then catching the error:
$('img').each(function()
{
$(this).error(function()
{
$(this).replaceWith(this.alt);
}).attr('src',$(this).prop('src'));
});
This, as in the Alexis contribution, has the benefit of removing the missing img image.
Before you begin, if you are uncomfortable with a command line, you can do all the following steps using SourceTree, GitExtension, GitHub Desktop, or your favorite tool.
To solve the issue, you might have two scenarios:
1) Fix only remote repository branch which is behind commit
Example: Both branches are on the remote side
ahead === Master branch
behind === Develop branch
Solution:
Clone the repository to the local workspace: this will give you the Master branch which is ahead with commit
git clone repositoryUrl
Create a branch with Develop name and checkout to that branch locally
git checkout -b DevelopBranchName // this command creates and checkout the branch
Pull from the remote Develop branch. Conflict might occur. if so, fix the conflict and commit the changes.
git pull origin DevelopBranchName
Merge the local Develop branch with the remote Develop branch
git merge origin develop
Push the merged branch to the remote Develop branch
git push origin develop
2) Local Master branch is behind the remote Master branch
This means every locally created branch is behind.
Before preceding, you have to commit or stash all the changes you made on the branch that is behind commits.
Solution:
Checkout your local Master branch
git checkout master
Pull from remote Master branch
git pull origin master
Now your local Master is in sync with the remote Branch but other local branches, that branched from the local Master branch, are not in sync with your local Master branch because of the above command. To fix that:
Checkout the branch that is behind your local Master branch
git checkout BranchNameBehindCommit
Merge with the local Master branch
git merge master // Now your branch is in sync with local Master branch
If this branch is on the remote repository, you have to push your changes
git push origin branchBehindCommit
Your code looks correct. My suggestion is that the database already thinks it's upgraded. If you executed the project after incrementing the version number, but before adding the execSQL
call, the database on your test device/emulator may already believe it's at version 2.
A quick way to verify this would be to change the version number to 3 -- if it upgrades after that, you know it was just because your device believed it was already upgraded.
Place single quotes around the Extended Properties
:
OleDbConnection oconn =
new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';");
Try it, it really works.
this
is the key (vs evt.target). See example.
document.body.addEventListener("click", function (evt) {_x000D_
console.dir(this);_x000D_
//note evt.target can be a nested element, not the body element, resulting in misfires_x000D_
console.log(evt.target);_x000D_
alert("body clicked");_x000D_
});
_x000D_
<h4>This is a heading.</h4>_x000D_
<p>this is a paragraph.</p>
_x000D_
Add a class:
.com_box:after {
content: '';
position: absolute;
left: 18px;
top: 50px;
width: 0;
height: 0;
border-left: 20px solid transparent;
border-right: 20px solid transparent;
border-top: 20px solid #000;
clear: both;
}
Updated your jsfiddle: http://jsfiddle.net/wrm4y8k6/8/
After upgrading from VS2013, I found that when debugging in Visual Studio 2015, it would freeze, I unchecked "Tools>Options>Debugging>General>Enable Diagnostics Tools while debugging" It brought debugging sessions back to normal. While Diagnostics are useful, I don't need them all the time so if at any point I need them I can turn it back on.
In the command line type service apache2 status
then hit enter. The result should say:
Apache2 is running (pid xxxx)
mysql> DROP INDEX email ON fuinfo;
where email is the unique key (rather than the column name). You find the name of the unique key by
mysql> SHOW CREATE TABLE fuinfo;
here you see the name of the unique key, which could be email_2, for example. So...
mysql> DROP INDEX email_2 ON fuinfo;
mysql> DESCRIBE fuinfo;
This should show that the index is removed
The startActivityForResult pattern is much better suited for what you're trying to achieve : http://developer.android.com/reference/android/app/Activity.html#StartingActivities
Try below code
public class MainActivity extends Activity {
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1=(TextView)findViewById(R.id.textView1);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
}
});
}
// Call Back method to get the Message form other Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
//do the things u wanted
}
}
}
SecondActivity.class
public class SecondActivity extends Activity {
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String message="hello ";
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(2,intent);
finish();//finishing activity
}
});
}
}
Let me know if it helped...
queryItems.AllKeys.Contains(key)
Be aware that key may not be unique and that the comparison is usually case sensitive. If you want to just get the value of the first matching key and not bothered about case then use this:
public string GetQueryValue(string queryKey)
{
foreach (string key in QueryItems)
{
if(queryKey.Equals(key, StringComparison.OrdinalIgnoreCase))
return QueryItems.GetValues(key).First(); // There might be multiple keys of the same name, but just return the first match
}
return null;
}
<?php
echo "<p>hello\n";
echo "world</p>";
echo "\n\n";
echo "<p>\n\tindented\n</p>\n";
echo "
<div>
easy formatting<br />
across multiple lines!
</div>
";
?>
<p>hello
world</p>
<p>
indented
</p>
<div>
easy formatting<br />
across multiple lines!
</div>
Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):
An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.
An array is an ordered sequence of zero or more values.
The terms "object" and "array" come from the conventions of JavaScript.
Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.
On Linux, if you call this inside the git repository folder:
git config http.sslVerify false
this will add sslVerify = false
in the [http]
section of the config
file in the .git
folder, which can also be the solution, if you want to add this manually with nano .git/config
:
...
[http]
sslVerify = false
Actually you have to Do Like below Example, which will help to Solve the Issue...
drop table ABC_table
create table ABC_table
(
names varchar(20),
age int
)
ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names
insert into ABC(age) values(10)
select * from ABC
Without Xcode: create file /usr/local/bin/xcodebuild
with content to cheat XcodeSelect
#!/bin/bash
exit 0
chmod +x /usr/local/bin/xcodebuild
SELECT *
FROM events
WHERE start <= '2013-07-22' OR end >= '2013-06-13'
After you edited your question it's cler you're using ASP.NET. Things are pretty different there (because in that case a roundtrip to server is pretty discouraged). You can do same things with JavaScript (but to handle globalization with toUpperCase()
may be a pain) or you can use CSS classes (relying on browsers implementation). Simply declare this CSS rule:
.upper-case
{
text-transform: uppercase
}
And add upper-case class to your text-box:
<asp:TextBox ID="TextBox1" CssClass="upper-case" runat="server"/>
but it capitalize characters after pressing Enter key.
It depends where you put that code. If you put it in, for example, TextChanged
event it'll make upper case as you type.
You have a property that do exactly what you need: CharacterCasing
:
TextBox1.CharacterCasing = CharacterCasing.Upper;
It works more or less but it doesn't handle locales very well. For example in German language ß is SS when converted in upper case (Institut für Deutsche Sprache) and this property doesn't handle that.
You may mimic CharacterCasing
property adding this code in KeyPress
event handler:
e.KeyChar = Char.ToUpper(e.KeyChar);
Unfortunately .NET framework doesn't handle this properly and upper case of sharp s character is returned unchanged. An upper case version of ß exists and it's ? and it may create some confusion, for example a word containing "ss" and another word containing "ß" can't be distinguished if you convert in upper case using "SS"). Don't forget that:
However, in 2010 the use of the capital sharp s became mandatory in official documentation when writing geographical names in all-caps.
There isn't much you can do unless you add proper code for support this (and others) subtle bugs in .NET localization. Best advice I can give you is to use a custom dictionary per each culture you need to support.
Finally don't forget that this transformation may be confusing for your users: in Turkey, for example, there are two different versions of i upper case letter.
If text processing is important in your application you can solve many issues using specialized DLLs for each locale you support like Word Processors do.
What I usually do is to do not use standard .NET functions for strings when I have to deal with culture specific issues (I keep them only for text in invariant culture). I create a Unicode class with static methods for everything I need (character counting, conversions, comparison) and many specialized derived classes for each supported language. At run-time that static methods will user current thread culture name to pick proper implementation from a dictionary and to delegate work to that. A skeleton may be something like this:
abstract class Unicode
{
public static string ToUpper(string text)
{
return GetConcreteClass().ToUpperCore(text);
}
protected virtual string ToUpperCore(string text)
{
// Default implementation, overridden in derived classes if needed
return text.ToUpper();
}
private Dictionary<string, Unicode> _implementations;
private Unicode GetConcreteClass()
{
string cultureName = Thread.Current.CurrentCulture.Name;
// Check if concrete class has been loaded and put in dictionary
...
return _implementations[cultureName];
}
}
I'll then have an implementation specific for German language:
sealed class German : Unicode
{
protected override string ToUpperCore(string text)
{
// Very naive implementation, just to provide an example
return text.ToUpper().Replace("ß", "?");
}
}
True implementation may be pretty more complicate (not all OSes supports upper case ?) but take as a proof of concept. See also this post for other details about Unicode issues on .NET.
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "USER_ID")
Long userId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> receiver;
}
public class Notification implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "NOTIFICATION_ID")
Long notificationId;
@Column(name = "TEXT")
String text;
@Column(name = "ALERT_STATUS")
@Enumerated(EnumType.STRING)
AlertStatus alertStatus = AlertStatus.NEW;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SENDER_ID")
@JsonIgnore
User sender;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "RECEIVER_ID")
@JsonIgnore
User receiver;
}
What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..
User model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
List<Notification> receiver;
Notification model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> **sender**;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> **receiver**;
I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.
You can use this helper class;
using System;
using System.Runtime.InteropServices;
/// <summary>
/// Provides detailed information about the host operating system.
/// </summary>
public static class OSInfo
{
#region BITS
/// <summary>
/// Determines if the current application is 32 or 64-bit.
/// </summary>
public static int Bits
{
get
{
return IntPtr.Size * 8;
}
}
#endregion BITS
#region EDITION
private static string s_Edition;
/// <summary>
/// Gets the edition of the operating system running on this computer.
/// </summary>
public static string Edition
{
get
{
if (s_Edition != null)
return s_Edition; //***** RETURN *****//
string edition = String.Empty;
OperatingSystem osVersion = Environment.OSVersion;
OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();
osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf( typeof( OSVERSIONINFOEX ) );
if (GetVersionEx( ref osVersionInfo ))
{
int majorVersion = osVersion.Version.Major;
int minorVersion = osVersion.Version.Minor;
byte productType = osVersionInfo.wProductType;
short suiteMask = osVersionInfo.wSuiteMask;
#region VERSION 4
if (majorVersion == 4)
{
if (productType == VER_NT_WORKSTATION)
{
// Windows NT 4.0 Workstation
edition = "Workstation";
}
else if (productType == VER_NT_SERVER)
{
if ((suiteMask & VER_SUITE_ENTERPRISE) != 0)
{
// Windows NT 4.0 Server Enterprise
edition = "Enterprise Server";
}
else
{
// Windows NT 4.0 Server
edition = "Standard Server";
}
}
}
#endregion VERSION 4
#region VERSION 5
else if (majorVersion == 5)
{
if (productType == VER_NT_WORKSTATION)
{
if ((suiteMask & VER_SUITE_PERSONAL) != 0)
{
// Windows XP Home Edition
edition = "Home";
}
else
{
// Windows XP / Windows 2000 Professional
edition = "Professional";
}
}
else if (productType == VER_NT_SERVER)
{
if (minorVersion == 0)
{
if ((suiteMask & VER_SUITE_DATACENTER) != 0)
{
// Windows 2000 Datacenter Server
edition = "Datacenter Server";
}
else if ((suiteMask & VER_SUITE_ENTERPRISE) != 0)
{
// Windows 2000 Advanced Server
edition = "Advanced Server";
}
else
{
// Windows 2000 Server
edition = "Server";
}
}
else
{
if ((suiteMask & VER_SUITE_DATACENTER) != 0)
{
// Windows Server 2003 Datacenter Edition
edition = "Datacenter";
}
else if ((suiteMask & VER_SUITE_ENTERPRISE) != 0)
{
// Windows Server 2003 Enterprise Edition
edition = "Enterprise";
}
else if ((suiteMask & VER_SUITE_BLADE) != 0)
{
// Windows Server 2003 Web Edition
edition = "Web Edition";
}
else
{
// Windows Server 2003 Standard Edition
edition = "Standard";
}
}
}
}
#endregion VERSION 5
#region VERSION 6
else if (majorVersion == 6)
{
int ed;
if (GetProductInfo( majorVersion, minorVersion,
osVersionInfo.wServicePackMajor, osVersionInfo.wServicePackMinor,
out ed ))
{
switch (ed)
{
case PRODUCT_BUSINESS:
edition = "Business";
break;
case PRODUCT_BUSINESS_N:
edition = "Business N";
break;
case PRODUCT_CLUSTER_SERVER:
edition = "HPC Edition";
break;
case PRODUCT_DATACENTER_SERVER:
edition = "Datacenter Server";
break;
case PRODUCT_DATACENTER_SERVER_CORE:
edition = "Datacenter Server (core installation)";
break;
case PRODUCT_ENTERPRISE:
edition = "Enterprise";
break;
case PRODUCT_ENTERPRISE_N:
edition = "Enterprise N";
break;
case PRODUCT_ENTERPRISE_SERVER:
edition = "Enterprise Server";
break;
case PRODUCT_ENTERPRISE_SERVER_CORE:
edition = "Enterprise Server (core installation)";
break;
case PRODUCT_ENTERPRISE_SERVER_CORE_V:
edition = "Enterprise Server without Hyper-V (core installation)";
break;
case PRODUCT_ENTERPRISE_SERVER_IA64:
edition = "Enterprise Server for Itanium-based Systems";
break;
case PRODUCT_ENTERPRISE_SERVER_V:
edition = "Enterprise Server without Hyper-V";
break;
case PRODUCT_HOME_BASIC:
edition = "Home Basic";
break;
case PRODUCT_HOME_BASIC_N:
edition = "Home Basic N";
break;
case PRODUCT_HOME_PREMIUM:
edition = "Home Premium";
break;
case PRODUCT_HOME_PREMIUM_N:
edition = "Home Premium N";
break;
case PRODUCT_HYPERV:
edition = "Microsoft Hyper-V Server";
break;
case PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT:
edition = "Windows Essential Business Management Server";
break;
case PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING:
edition = "Windows Essential Business Messaging Server";
break;
case PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY:
edition = "Windows Essential Business Security Server";
break;
case PRODUCT_SERVER_FOR_SMALLBUSINESS:
edition = "Windows Essential Server Solutions";
break;
case PRODUCT_SERVER_FOR_SMALLBUSINESS_V:
edition = "Windows Essential Server Solutions without Hyper-V";
break;
case PRODUCT_SMALLBUSINESS_SERVER:
edition = "Windows Small Business Server";
break;
case PRODUCT_STANDARD_SERVER:
edition = "Standard Server";
break;
case PRODUCT_STANDARD_SERVER_CORE:
edition = "Standard Server (core installation)";
break;
case PRODUCT_STANDARD_SERVER_CORE_V:
edition = "Standard Server without Hyper-V (core installation)";
break;
case PRODUCT_STANDARD_SERVER_V:
edition = "Standard Server without Hyper-V";
break;
case PRODUCT_STARTER:
edition = "Starter";
break;
case PRODUCT_STORAGE_ENTERPRISE_SERVER:
edition = "Enterprise Storage Server";
break;
case PRODUCT_STORAGE_EXPRESS_SERVER:
edition = "Express Storage Server";
break;
case PRODUCT_STORAGE_STANDARD_SERVER:
edition = "Standard Storage Server";
break;
case PRODUCT_STORAGE_WORKGROUP_SERVER:
edition = "Workgroup Storage Server";
break;
case PRODUCT_UNDEFINED:
edition = "Unknown product";
break;
case PRODUCT_ULTIMATE:
edition = "Ultimate";
break;
case PRODUCT_ULTIMATE_N:
edition = "Ultimate N";
break;
case PRODUCT_WEB_SERVER:
edition = "Web Server";
break;
case PRODUCT_WEB_SERVER_CORE:
edition = "Web Server (core installation)";
break;
}
}
}
#endregion VERSION 6
}
s_Edition = edition;
return edition;
}
}
#endregion EDITION
#region NAME
private static string s_Name;
/// <summary>
/// Gets the name of the operating system running on this computer.
/// </summary>
public static string Name
{
get
{
if (s_Name != null)
return s_Name; //***** RETURN *****//
string name = "unknown";
OperatingSystem osVersion = Environment.OSVersion;
OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();
osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf( typeof( OSVERSIONINFOEX ) );
if (GetVersionEx( ref osVersionInfo ))
{
int majorVersion = osVersion.Version.Major;
int minorVersion = osVersion.Version.Minor;
switch (osVersion.Platform)
{
case PlatformID.Win32Windows:
{
if (majorVersion == 4)
{
string csdVersion = osVersionInfo.szCSDVersion;
switch (minorVersion)
{
case 0:
if (csdVersion == "B" || csdVersion == "C")
name = "Windows 95 OSR2";
else
name = "Windows 95";
break;
case 10:
if (csdVersion == "A")
name = "Windows 98 Second Edition";
else
name = "Windows 98";
break;
case 90:
name = "Windows Me";
break;
}
}
break;
}
case PlatformID.Win32NT:
{
byte productType = osVersionInfo.wProductType;
switch (majorVersion)
{
case 3:
name = "Windows NT 3.51";
break;
case 4:
switch (productType)
{
case 1:
name = "Windows NT 4.0";
break;
case 3:
name = "Windows NT 4.0 Server";
break;
}
break;
case 5:
switch (minorVersion)
{
case 0:
name = "Windows 2000";
break;
case 1:
name = "Windows XP";
break;
case 2:
name = "Windows Server 2003";
break;
}
break;
case 6:
switch (productType)
{
case 1:
name = "Windows Vista";
break;
case 3:
name = "Windows Server 2008";
break;
}
break;
}
break;
}
}
}
s_Name = name;
return name;
}
}
#endregion NAME
#region PINVOKE
#region GET
#region PRODUCT INFO
[DllImport( "Kernel32.dll" )]
internal static extern bool GetProductInfo(
int osMajorVersion,
int osMinorVersion,
int spMajorVersion,
int spMinorVersion,
out int edition );
#endregion PRODUCT INFO
#region VERSION
[DllImport( "kernel32.dll" )]
private static extern bool GetVersionEx( ref OSVERSIONINFOEX osVersionInfo );
#endregion VERSION
#endregion GET
#region OSVERSIONINFOEX
[StructLayout( LayoutKind.Sequential )]
private struct OSVERSIONINFOEX
{
public int dwOSVersionInfoSize;
public int dwMajorVersion;
public int dwMinorVersion;
public int dwBuildNumber;
public int dwPlatformId;
[MarshalAs( UnmanagedType.ByValTStr, SizeConst = 128 )]
public string szCSDVersion;
public short wServicePackMajor;
public short wServicePackMinor;
public short wSuiteMask;
public byte wProductType;
public byte wReserved;
}
#endregion OSVERSIONINFOEX
#region PRODUCT
private const int PRODUCT_UNDEFINED = 0x00000000;
private const int PRODUCT_ULTIMATE = 0x00000001;
private const int PRODUCT_HOME_BASIC = 0x00000002;
private const int PRODUCT_HOME_PREMIUM = 0x00000003;
private const int PRODUCT_ENTERPRISE = 0x00000004;
private const int PRODUCT_HOME_BASIC_N = 0x00000005;
private const int PRODUCT_BUSINESS = 0x00000006;
private const int PRODUCT_STANDARD_SERVER = 0x00000007;
private const int PRODUCT_DATACENTER_SERVER = 0x00000008;
private const int PRODUCT_SMALLBUSINESS_SERVER = 0x00000009;
private const int PRODUCT_ENTERPRISE_SERVER = 0x0000000A;
private const int PRODUCT_STARTER = 0x0000000B;
private const int PRODUCT_DATACENTER_SERVER_CORE = 0x0000000C;
private const int PRODUCT_STANDARD_SERVER_CORE = 0x0000000D;
private const int PRODUCT_ENTERPRISE_SERVER_CORE = 0x0000000E;
private const int PRODUCT_ENTERPRISE_SERVER_IA64 = 0x0000000F;
private const int PRODUCT_BUSINESS_N = 0x00000010;
private const int PRODUCT_WEB_SERVER = 0x00000011;
private const int PRODUCT_CLUSTER_SERVER = 0x00000012;
private const int PRODUCT_HOME_SERVER = 0x00000013;
private const int PRODUCT_STORAGE_EXPRESS_SERVER = 0x00000014;
private const int PRODUCT_STORAGE_STANDARD_SERVER = 0x00000015;
private const int PRODUCT_STORAGE_WORKGROUP_SERVER = 0x00000016;
private const int PRODUCT_STORAGE_ENTERPRISE_SERVER = 0x00000017;
private const int PRODUCT_SERVER_FOR_SMALLBUSINESS = 0x00000018;
private const int PRODUCT_SMALLBUSINESS_SERVER_PREMIUM = 0x00000019;
private const int PRODUCT_HOME_PREMIUM_N = 0x0000001A;
private const int PRODUCT_ENTERPRISE_N = 0x0000001B;
private const int PRODUCT_ULTIMATE_N = 0x0000001C;
private const int PRODUCT_WEB_SERVER_CORE = 0x0000001D;
private const int PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT = 0x0000001E;
private const int PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY = 0x0000001F;
private const int PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING = 0x00000020;
private const int PRODUCT_SERVER_FOR_SMALLBUSINESS_V = 0x00000023;
private const int PRODUCT_STANDARD_SERVER_V = 0x00000024;
private const int PRODUCT_ENTERPRISE_SERVER_V = 0x00000026;
private const int PRODUCT_STANDARD_SERVER_CORE_V = 0x00000028;
private const int PRODUCT_ENTERPRISE_SERVER_CORE_V = 0x00000029;
private const int PRODUCT_HYPERV = 0x0000002A;
#endregion PRODUCT
#region VERSIONS
private const int VER_NT_WORKSTATION = 1;
private const int VER_NT_DOMAIN_CONTROLLER = 2;
private const int VER_NT_SERVER = 3;
private const int VER_SUITE_SMALLBUSINESS = 1;
private const int VER_SUITE_ENTERPRISE = 2;
private const int VER_SUITE_TERMINAL = 16;
private const int VER_SUITE_DATACENTER = 128;
private const int VER_SUITE_SINGLEUSERTS = 256;
private const int VER_SUITE_PERSONAL = 512;
private const int VER_SUITE_BLADE = 1024;
#endregion VERSIONS
#endregion PINVOKE
#region SERVICE PACK
/// <summary>
/// Gets the service pack information of the operating system running on this computer.
/// </summary>
public static string ServicePack
{
get
{
string servicePack = String.Empty;
OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();
osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf( typeof( OSVERSIONINFOEX ) );
if (GetVersionEx( ref osVersionInfo ))
{
servicePack = osVersionInfo.szCSDVersion;
}
return servicePack;
}
}
#endregion SERVICE PACK
#region VERSION
#region BUILD
/// <summary>
/// Gets the build version number of the operating system running on this computer.
/// </summary>
public static int BuildVersion
{
get
{
return Environment.OSVersion.Version.Build;
}
}
#endregion BUILD
#region FULL
#region STRING
/// <summary>
/// Gets the full version string of the operating system running on this computer.
/// </summary>
public static string VersionString
{
get
{
return Environment.OSVersion.Version.ToString();
}
}
#endregion STRING
#region VERSION
/// <summary>
/// Gets the full version of the operating system running on this computer.
/// </summary>
public static Version Version
{
get
{
return Environment.OSVersion.Version;
}
}
#endregion VERSION
#endregion FULL
#region MAJOR
/// <summary>
/// Gets the major version number of the operating system running on this computer.
/// </summary>
public static int MajorVersion
{
get
{
return Environment.OSVersion.Version.Major;
}
}
#endregion MAJOR
#region MINOR
/// <summary>
/// Gets the minor version number of the operating system running on this computer.
/// </summary>
public static int MinorVersion
{
get
{
return Environment.OSVersion.Version.Minor;
}
}
#endregion MINOR
#region REVISION
/// <summary>
/// Gets the revision version number of the operating system running on this computer.
/// </summary>
public static int RevisionVersion
{
get
{
return Environment.OSVersion.Version.Revision;
}
}
#endregion REVISION
#endregion VERSION
}
Sample code is here:
Console.WriteLine( "Operation System Information" );
Console.WriteLine( "----------------------------" );
Console.WriteLine( "Name = {0}", OSInfo.Name );
Console.WriteLine( "Edition = {0}", OSInfo.Edition );
Console.WriteLine( "Service Pack = {0}", OSInfo.ServicePack );
Console.WriteLine( "Version = {0}", OSInfo.VersionString );
Console.WriteLine( "Bits = {0}", OSInfo.Bits );
I was found at this address : http://www.csharp411.com/wp-content/uploads/2009/01/OSInfo.cs
Recently ran into a problem with this and a Chrome extension that was corrupting a JSON stream when the response header labeled the content-type as 'text/html' apparently extensions can and will use the response header to alter the content prior to further processing by the browser. Changing the content-type fixed the issue.
I believe you can do this using a cast:
float f_val = 3.6f;
int i_val = (int) f_val;
You also follow this code:
var response = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent("Users doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
StatusCode = HttpStatusCode.NotFound
}
throw new HttpResponseException(response);
mysql> set innodb_lock_wait_timeout=100
Query OK, 0 rows affected (0.02 sec)
mysql> show variables like 'innodb_lock_wait_timeout';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| innodb_lock_wait_timeout | 100 |
+--------------------------+-------+
Now trigger the lock again. You have 100 seconds time to issue a SHOW ENGINE INNODB STATUS\G
to the database and see which other transaction is locking yours.
NSIntegers are not objects, you cast them to long
, in order to match the current 64-bit architectures' definition:
NSString *inStr = [NSString stringWithFormat: @"%ld", (long)month];
Machine learning is a field where you are trying to make machine to mimic the human behavior.
You train machine just like a baby.The way humans learn, identify features, recognize patterns and train himself, same way you train machine by feeding data with various features. Machine algorithm identify the pattern within the data and classify it into particular category.
Machine learning broadly divided into two category, supervised and unsupervised learning.
Supervised learning is the concept where you have input vector / data with corresponding target value (output).On the other hand unsupervised learning is the concept where you only have input vectors / data without any corresponding target value.
An example of supervised learning is handwritten digits recognition where you have image of digits with corresponding digit [0-9], and an example of unsupervised learning is grouping customers by purchasing behavior.
The solution suggested from arlomedia worked for me. About his issue of extraspace I solved removing all the paddings to the switch.
EDIT
As requested, here what I have.
In the layout file, my switch is inside a linear layout and after a TextView.
<LinearLayout
android:id="@+id/myLinearLayout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal|center"
android:gravity="right"
android:padding="10dp"
android:layout_marginTop="0dp"
android:background="@drawable/bkg_myLinearLayout"
android:layout_marginBottom="0dp">
<TextView
android:id="@+id/myTextForTheSwitch"
android:layout_height="wrap_content"
android:text="@string/TextForTheSwitch"
android:textSize="18sp"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal|center"
android:gravity="right"
android:layout_width="wrap_content"
android:paddingRight="20dp"
android:textColor="@color/text_white" />
<Switch
android:id="@+id/mySwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="@string/On"
android:textOff="@string/Off"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:layout_toRightOf="@id/myTextForTheSwitch"
android:layout_alignBaseline="@id/myTextForTheSwitch"
android:gravity="right" />
</LinearLayout>
Since I'm working with Xamarin / Monodroid (min. Android 4.1) my code is:
Android.Graphics.Color colorOn = Android.Graphics.Color.Green;
Android.Graphics.Color colorOff = Android.Graphics.Color.Gray;
Android.Graphics.Color colorDisabled = Android.Graphics.Color.Green;
StateListDrawable drawable = new StateListDrawable();
drawable.AddState(new int[] { Android.Resource.Attribute.StateChecked }, new ColorDrawable(colorOn));
drawable.AddState(new int[] { -Android.Resource.Attribute.StateEnabled }, new ColorDrawable(colorDisabled));
drawable.AddState(new int[] { }, new ColorDrawable(colorOff));
swtch_EnableEdit.ThumbDrawable = drawable;
swtch_EnableEdit is previously defined like this (Xamarin):
Switch swtch_EnableEdit = view.FindViewById<Switch>(Resource.Id.mySwitch);
I don't set at all the paddings and I don't call .setPadding(0, 0, 0, 0).
I Faced the same issue while installing a setup using a jar file. Solution thta worked for me is
java -jar <<jar fully qualified path>>
It worked for me :)
You set the style per element and not by its content:
function init() {
document.getElementById("about").style.color = 'blue';
}
With innerHTML
you get/set the content of an element. So if you would want to modify your title, innerHTML
would be the way to go.
In your case, however, you just want to modify a property of the element (change the color of the text inside it), so you address the style
property of the element itself.
Try this:
function explode(){
alert("Boom!");
}
setTimeout(explode, 2000);
You should use other variable:
$m=0;
for($n=1; $n<=8; $n++):
$n = $n + $m;
$m++;
echo '<p>'. $n .'</p>';
endfor;
You can use backticks (also known as accent graves) or $()
.
Like:
OUTPUT=$(x+2);
OUTPUT=`x+2`;
Both have the same effect. But OUTPUT=$(x+2) is more readable and the latest one.
Necromancing.
The provided answers are incomplete.
First, as already said, you cannot add multiple allow-from hosts, that's not supported.
Second, you need to dynamically extract that value from the HTTP referrer, which means that you can't add the value to Web.config, because it's not always the same value.
It will be necessary to do browser-detection to avoid adding allow-from when the browser is Chrome (it produces an error on the debug - console, which can quickly fill the console up, or make the application slow). That also means you need to modify the ASP.NET browser detection, as it wrongly identifies Edge as Chrome.
This can be done in ASP.NET by writing a HTTP-module which runs on every request, that appends a http-header for every response, depending on the request's referrer. For Chrome, it needs to add Content-Security-Policy.
// https://stackoverflow.com/questions/31870789/check-whether-browser-is-chrome-or-edge
public class BrowserInfo
{
public System.Web.HttpBrowserCapabilities Browser { get; set; }
public string Name { get; set; }
public string Version { get; set; }
public string Platform { get; set; }
public bool IsMobileDevice { get; set; }
public string MobileBrand { get; set; }
public string MobileModel { get; set; }
public BrowserInfo(System.Web.HttpRequest request)
{
if (request.Browser != null)
{
if (request.UserAgent.Contains("Edge")
&& request.Browser.Browser != "Edge")
{
this.Name = "Edge";
}
else
{
this.Name = request.Browser.Browser;
this.Version = request.Browser.MajorVersion.ToString();
}
this.Browser = request.Browser;
this.Platform = request.Browser.Platform;
this.IsMobileDevice = request.Browser.IsMobileDevice;
if (IsMobileDevice)
{
this.Name = request.Browser.Browser;
}
}
}
}
void context_EndRequest(object sender, System.EventArgs e)
{
if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
try
{
// response.Headers["P3P"] = "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"":
// response.Headers.Set("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
// response.AddHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
response.AppendHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
// response.AppendHeader("X-Frame-Options", "DENY");
// response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
// response.AppendHeader("X-Frame-Options", "AllowAll");
if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
{
// "X-Frame-Options": "ALLOW-FROM " Not recognized in Chrome
string host = System.Web.HttpContext.Current.Request.UrlReferrer.Scheme + System.Uri.SchemeDelimiter
+ System.Web.HttpContext.Current.Request.UrlReferrer.Authority
;
string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;
// SQL.Log(System.Web.HttpContext.Current.Request.RawUrl, System.Web.HttpContext.Current.Request.UrlReferrer.OriginalString, refAuth);
if (IsHostAllowed(refAuth))
{
BrowserInfo bi = new BrowserInfo(System.Web.HttpContext.Current.Request);
// bi.Name = Firefox
// bi.Name = InternetExplorer
// bi.Name = Chrome
// Chrome wants entire path...
if (!System.StringComparer.OrdinalIgnoreCase.Equals(bi.Name, "Chrome"))
response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);
// unsafe-eval: invalid JSON https://github.com/keen/keen-js/issues/394
// unsafe-inline: styles
// data: url(data:image/png:...)
// https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet
// https://www.ietf.org/rfc/rfc7034.txt
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
// https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
// https://stackoverflow.com/questions/10205192/x-frame-options-allow-from-multiple-domains
// https://content-security-policy.com/
// http://rehansaeed.com/content-security-policy-for-asp-net-mvc/
// This is for Chrome:
// response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);
System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
ls.Add("default-src");
ls.Add("'self'");
ls.Add("'unsafe-inline'");
ls.Add("'unsafe-eval'");
ls.Add("data:");
// http://az416426.vo.msecnd.net/scripts/a/ai.0.js
// ls.Add("*.msecnd.net");
// ls.Add("vortex.data.microsoft.com");
ls.Add(selfAuth);
ls.Add(refAuth);
string contentSecurityPolicy = string.Join(" ", ls.ToArray());
response.AppendHeader("Content-Security-Policy", contentSecurityPolicy);
}
else
{
response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
}
}
else
response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
}
catch (System.Exception ex)
{
// WTF ?
System.Console.WriteLine(ex.Message); // Suppress warning
}
} // End if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)
} // End Using context_EndRequest
private static string[] s_allowedHosts = new string[]
{
"localhost:49533"
,"localhost:52257"
,"vmcompany1"
,"vmcompany2"
,"vmpostalservices"
,"example.com"
};
public static bool IsHostAllowed(string host)
{
return Contains(s_allowedHosts, host);
} // End Function IsHostAllowed
public static bool Contains(string[] allowed, string current)
{
for (int i = 0; i < allowed.Length; ++i)
{
if (System.StringComparer.OrdinalIgnoreCase.Equals(allowed[i], current))
return true;
} // Next i
return false;
} // End Function Contains
You need to register the context_EndRequest function in the HTTP-module Init function.
public class RequestLanguageChanger : System.Web.IHttpModule
{
void System.Web.IHttpModule.Dispose()
{
// throw new NotImplementedException();
}
void System.Web.IHttpModule.Init(System.Web.HttpApplication context)
{
// https://stackoverflow.com/questions/441421/httpmodule-event-execution-order
context.EndRequest += new System.EventHandler(context_EndRequest);
}
// context_EndRequest Code from above comes here
}
Next you need to add the module to your application. You can either do this programmatically in Global.asax by overriding the Init function of the HttpApplication, like this:
namespace ChangeRequestLanguage
{
public class Global : System.Web.HttpApplication
{
System.Web.IHttpModule mod = new libRequestLanguageChanger.RequestLanguageChanger();
public override void Init()
{
mod.Init(this);
base.Init();
}
protected void Application_Start(object sender, System.EventArgs e)
{
}
protected void Session_Start(object sender, System.EventArgs e)
{
}
protected void Application_BeginRequest(object sender, System.EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, System.EventArgs e)
{
}
protected void Application_Error(object sender, System.EventArgs e)
{
}
protected void Session_End(object sender, System.EventArgs e)
{
}
protected void Application_End(object sender, System.EventArgs e)
{
}
}
}
or you can add entries to Web.config if you don't own the application source-code:
<httpModules>
<add name="RequestLanguageChanger" type= "libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<add name="RequestLanguageChanger" type="libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
</modules>
</system.webServer>
</configuration>
The entry in system.webServer is for IIS7+, the other in system.web is for IIS 6.
Note that you need to set runAllManagedModulesForAllRequests to true, for that it works properly.
The string in type is in the format "Namespace.Class, Assembly"
.
Note that if you write your assembly in VB.NET instead of C#, VB creates a default-Namespace for each project, so your string will look like
"[DefaultNameSpace.Namespace].Class, Assembly"
If you want to avoid this problem, write the DLL in C#.
random.sample(population, k)
It is used for randomly sampling a sample of length 'k'
from a population. returns a 'k'
length list of unique elements chosen from the population sequence or set
it returns a new list and leaves the original population unchanged and the resulting list is in selection order so that all sub-slices will also be valid random samples
I am putting up an example in which I am splitting a dataset randomly. It is basically a function in which you pass x_train(population)
as an argument and return indices of 60%
of the data as D_test
.
import random
def randomly_select_70_percent_of_data_from_1_to_length(x_train):
return random.sample(range(0, len(x_train)), int(0.6*len(x_train)))
I know it's a bit late but I had issues with a modal window not allowing some links on the menu bar to work, even when it has not been triggered. But I solved it by doing the following:
.modal{
display:none;
}
Short answer: While it's technically possible to send 100k e-mails each week yourself, the simplest, easiest and cheapest solution is to outsource this to one of the companies that specialize in it (I did say "cheapest": there's no limit to the amount of development time (and therefore money) that you can sink into this when trying to DIY).
Long answer: If you decide that you absolutely want to do this yourself, prepare for a world of hurt (after all, this is e-mail/e-fail we're talking about). You'll need:
mail()
is horrible enough by itself)Surprisingly, that was the easy part. The hard part is actually sending it:
And to top it off, you'll have to manage the legal part of it (various federal, state, and local laws; and even different tangles of laws once you send outside the U.S. (note: you have no way of finding if [email protected] lives in Southwest Elbonia, the country with world's most draconian antispam laws)).
I'm pretty sure I missed a few heads of this hydra - are you still sure you want to do this yourself? If so, there'll be another wave, this time merely the annoying problems inherent in sending an e-mail. (You see, SMTP is a store-and-forward protocol, which means that your e-mail will be shuffled across many SMTP servers around the Internet, in the hope that the next one is a bit closer to the final recipient. Basically, the e-mail is sent to an SMTP server, which puts it into its forward queue; when time comes, it will forward it further to a different SMTP server, until it reaches the SMTP server for the given domain. This forward could happen immediately, or in a few minutes, or hours, or days, or never.) Thus, you'll see the following issues - most of which could happen en route as well as at the destination:
<blink>
is not your friend here, nor is <font color=...>
)and it'll be your job to troubleshoot and solve this (hint: you can't, mostly). The people who run a legit mass-mailing businesses know that in the end you can't solve it, and that they can't solve it either - and they have the reasons well researched, documented and outlined (maybe even as a Powerpoint presentation - complete with sounds and cool transitions - that your bosses can understand), as they've had to explain this a million times before. Plus, for the problems that are actually solvable, they know very well how to solve them.
If, after all this, you are not discouraged and still want to do this, go right ahead: it's even possible that you'll find a better way to do this. Just know that the road ahead won't be easy - sending e-mail is trivial, getting it delivered is hard.
This should do the trick:
pw_bytes.decode("utf-8")
Also note that you cannot normally set a value for an IDENTITY column. You can, however, specify the identity of rows if you set IDENTITY_INSERT to ON for your table. For example:
SET IDENTITY_INSERT Orders ON
-- do inserts here
SET IDENTITY_INSERT Orders OFF
This insert will reset the identity to the last inserted value. From MSDN:
If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value.
Unicode is not an encoding - to quote Kumar McMillan:
If ASCII, UTF-8, and other byte strings are "text" ...
...then Unicode is "text-ness";
it is the abstract form of text
Have a read of McMillan's Unicode In Python, Completely Demystified talk from PyCon 2008, it explains things a lot better than most of the related answers on Stack Overflow.
Difference between SASS and SCSS article explains the difference in details. Don’t be confused by the SASS and SCSS options, although I also was initially, .scss is Sassy CSS and is the next generation of .sass.
If that didn’t make sense you can see the difference in code below.
/* SCSS */
$blue: #3bbfce;
$margin: 16px;
.content-navigation {
border-color: $blue;
color: darken($blue, 9%);
}
.border {
padding: $margin / 2; margin: $margin / 2; border-color: $blue;
}
In the code above we use ; to separate the declarations. I’ve even added all the declarations for .border onto a single line to illustrate this point further. In contrast, the SASS code below must be on different lines with indentation and there is no use of the ;.
/* SASS */
$blue: #3bbfce
$margin: 16px
.content-navigation
border-color: $blue
color: darken($blue, 9%)
.border
padding: $margin / 2
margin: $margin / 2
border-color: $blue
You can see from the CSS below that the SCSS style is a lot more similar to regular CSS than the older SASS approach.
/* CSS */
.content-navigation {
border-color: #3bbfce;
color: #2b9eab;
}
.border {
padding: 8px;
margin: 8px;
border-color: #3bbfce;
}
I think most of the time these days if someone mentions that they are working with Sass they are referring to authoring in .scss rather than the traditional .sass way.
To get make to actually ignore errors on a single line, you can simply suffix it with ; true
, setting the return value to 0. For example:
rm .lambda .lambda_t .activity .activity_t_lambda 2>/dev/null; true
This will redirect stderr output to null, and follow the command with true (which always returns 0, causing make to believe the command succeeded regardless of what actually happened), allowing program flow to continue.
Try this , there is no need to set its a CLOB
public static void main(String[] args)
{
try{
System.out.println("Opening db");
Class.forName("oracle.jdbc.driver.OracleDriver");
if(con==null)
con=DriverManager.getConnection("jdbc:oracle:thin:@192.9.200.103:1521: orcl","sas","sas");
if(stmt==null)
stmt=con.createStatement();
int res=9;
String usersSql = "{call Esme_Insertsmscdata(?,?,?,?,?)}";
CallableStatement stmt = con.prepareCall(usersSql);
// THIS THE CLOB DATA
stmt.setString(1,"SS¶5268771¶00058711¶04192018¶SS¶5268771¶00058712¶04192018¶SS¶5268772¶00058713¶04192018¶SS¶5268772¶00058714¶04192018¶SS¶5268773¶00058715¶04192018¶SS¶5268773¶00058716¶04192018¶SS¶5268774¶00058717¶04192018¶SS¶5268774¶00058718¶04192018¶SS¶5268775¶00058719¶04192018¶SS¶5268775¶00058720¶04192018¶");
stmt.setString(2, "bcvbcvb");
stmt.setString(3, String.valueOf("4522"));
stmt.setString(4, "42.25.632.25");
stmt.registerOutParameter(5,OracleTypes.NUMBER);
stmt.execute();
res=stmt.getInt(5);
stmt.close();
System.out.println(res);
}
catch(Exception e)
{
try
{
con.close();
} catch (SQLException e1) {
}
}
}
}
Use -1
index (negative indices count backward from the end of the array):
a[-1] # => 5
b[-1] # => 6
or Array#last
method:
a.last # => 5
b.last # => 6
The user of this question was using Docker version 0.9.1, build 867b2a9
, I will give you an answer for docker version >= 17.06.
What you want, keep local directory synchronized within container directory, is accomplished by mounting the volume with type bind
. This will bind the source (your system) and the target (at the docker container) directories. It's almost the same as mounting a directory on linux.
According to Docker documentation, the appropriate command to mount is now mount
instead of -v
. Here's its documentation:
--mount
: Consists of multiple key-value pairs, separated by commas. Each key/value pair takes the form of a <key>=<value>
tuple. The --mount
syntax is more verbose than -v
or --volume
, but the order of the keys is not significant, and the value of the flag is easier to understand.
The type
of the mount, which can be bind
, volume
, or tmpfs
. (We are going to use bind)
The source
of the mount. For bind mounts, this is the path to the file or directory on the Docker daemon host. May be specified as source
or src
.
The destination
takes as its value the path where the file or directory will be mounted in the container. May be specified as destination
, dst
, or target
.
So, to mount the the current directory (source) with /test_container
(target) we are going to use:
docker run -it --mount src="$(pwd)",target=/test_container,type=bind k3_s3
If these mount parameters have spaces you must put quotes around them. When I know they don't, I would use `pwd`
instead:
docker run -it --mount src=`pwd`,target=/test_container,type=bind k3_s3
You will also have to deal with file permission, see this article.
try this way
var url_string = window.location;
var url = new URL(url_string);
var name = url.searchParams.get("name");
var tvid = url.searchParams.get("id");
Just a guess, but I think with the SYSTEM_ALERT_WINDOW permission (displayed as "Draw over other apps", see here) it could be possible: display your app as a fullscreen, system alert type window. This way it will hide any other apps, even the homescreen so if you press Home, it won't really be disabled, just without any visible effect.
MX Player has this permission declared, and Facebook Messenger has it too for displaying "chat heads" over anything - so it might be the solution.
Update (added from my comments): Next, use SYSTEM_UI_FLAG_HIDE_NAVIGATION in conjunction with capturing touch events/using OnSystemUiVisibilityChangeListener to override the default behaviour (navbar appearing on touch). Also, since you said exit immersive gesture does not work, you could try setting SYSTEM_UI_FLAG_IMMERSIVE_STICKY too (with SYSTEM_UI_FLAG_FULLSCREEN and SYSTEM_UI_FLAG_HIDE_NAVIGATION).
You could create a commit which contains an empty working copy.
This is a generally safe, non-destructive approach because it does not involve the use of any brute-force reset mechanisms. First you hide all managed content with git checkout empty
, then you are free to manually review and remove whatever unmanaged content remains.
## create a stand-alone, tagged, empty commit
true | git mktree | xargs git commit-tree | xargs git tag empty
## clear the working copy
git checkout empty
Your working copy should now be clear of any managed content. All that remains are unmanaged files and the .git
folder itself.
To re-populate your working copy...
git checkout master ## or whatever branch you will be using
If you're a forward thinking individual, you might start your repository off on the right foot by basing everything on an initial empty commit...
git init
git commit --allow-empty --allow-empty-message -m ""
git tag empty
...
There are various uses for a tagged empty worktree. My favorite at the moment is to depopulate the root under a set of git worktree
subfolders.
Just for the sake of academic interest, I did it this way...
(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day
The package broom
comes in handy here (it uses the "tidy" format).
tidy(mg)
will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).
Example from broom
's github repo:
lmfit <- lm(mpg ~ wt, mtcars)
require(broom)
tidy(lmfit)
term estimate std.error statistic p.value
1 (Intercept) 37.285 1.8776 19.858 8.242e-19
2 wt -5.344 0.5591 -9.559 1.294e-10
is.data.frame(tidy(lmfit))
[1] TRUE
I completely forgot that I had previously installed another version of Apache Tomcat, which was causing this problem. So, just try uninstalling the previous version. Hope it helps.
Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.
This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.
To change the datasource connection, go the Database menu and click Set Datasource Location.
And try running the report again.
The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.
To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.
If you are using WPF, there is an awesome tool : WPF Inspector.
It attaches itself to a WPF app and display the full tree of controls with the all properties, an it allows you (amongst other things) to break on any property change.
But sadly I didn't find any tool that would allow you to do the same with ANY property or variable.
I just had the same problem.
Here is an answer that doesn't use any explicit file writing in your main code (letting the api taking care of it for you).
Drawable mDrawable = myImageView1.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image I want to share", null);
Uri uri = Uri.parse(path);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image"));
This is the path... you just need to add your image IDs in a Drawable object. In my case (code above), the drawable was extracted from an ImageView.
There is another approach. In my example you see some business logic in repository class that I use with dependency injection in ASP .NET MVC Core 3.1.
And here I want to get connectiongString
for that business logic because probably another repository will have access to another database at all.
This pattern allows you in the same business logic repository have access to different databases.
C#
public interface IStatsRepository
{
IEnumerable<FederalDistrict> FederalDistricts();
}
class StatsRepository : IStatsRepository
{
private readonly DbContextOptionsBuilder<EFCoreTestContext>
optionsBuilder = new DbContextOptionsBuilder<EFCoreTestContext>();
private readonly IConfigurationRoot configurationRoot;
public StatsRepository()
{
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
configurationRoot = configurationBuilder.Build();
}
public IEnumerable<FederalDistrict> FederalDistricts()
{
var conn = configurationRoot.GetConnectionString("EFCoreTestContext");
optionsBuilder.UseSqlServer(conn);
using (var ctx = new EFCoreTestContext(optionsBuilder.Options))
{
return ctx.FederalDistricts.Include(x => x.FederalSubjects).ToList();
}
}
}
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"EFCoreTestContext": "Data Source=DESKTOP-GNJKL2V\\MSSQLSERVER2014;Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
I had an emulator running but the VSC ide could not connect to it. So I enabled developer mode in the emulator and the debugging options as well. Voila, It worked!
From the menu bar: Project -> Properties -> Java Compiler
Enable project specific settings (checked) Uncheck "use Compliance from execution environment '.... Select the desired "compiler compliance level"
That will allow you to compile "1.5" code using a "1.6" JDK.
If you want to acutally use a 1.5 JDK to produce "1.5" compliant code, then install a suitable 1.5 JDK and tell eclipse where it is installed via:
Window -> preferences -> Installed JREs
And then go back to your project
Project -> properties -> Java Build Path -> libraries
remove the 1.6 system libaries, and: add library... -> JRE System LIbrary -> Alternate JRE -> The JRE you want.
Verify that the correct JRE is on the project's build path, save everything, and enjoy!
In WSL, there seems to be a problem with path conversion. The location of the Dockerfile in Ubuntu (where I'm running docker and where Dockerfile lives) is "/home/sxw455/App1", but neither of these commands worked:
$ pwd
/home/sxw455/App1
$ ll
total 4
drwxrwxrwx 0 sxw455 sxw455 4096 Dec 11 19:28 ./
drwxr-xr-x 0 sxw455 sxw455 4096 Dec 11 19:25 ../
-rwxrwxrwx 1 sxw455 sxw455 531 Dec 11 19:26 Dockerfile*
-rwxrwxrwx 1 sxw455 sxw455 666 Dec 11 19:28 app.py*
-rwxrwxrwx 1 sxw455 sxw455 12 Dec 11 19:27 requirements.txt*
$ docker build -t friendlyhello .
unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx C:\Windows\System32\Dockerfile: The system cannot find the file specified.
$ docker build -t friendlyhello "/home/sxw455/App1"
unable to prepare context: path "/home/sxw455/App1" not found
But in Windows, the actual path is:
C:\Users\sxw455\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc\LocalState\rootfs\home\sxw455\App1
And so I had to do this (even though I ran it from bash):
$ docker build -t friendlyhello
"C:\Users\sxw455\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc\LocalState\rootfs\home\sxw455\App1"
Sending build context to Docker daemon 5.12kB
Step 1/7 : FROM python:2.7-slim
---> 0dc3d8d47241
Step 2/7 : WORKDIR /app
---> Using cache
---> f739aa02ce04
Step 3/7 : COPY . /app
---> Using cache
---> 88686c524ae9
Step 4/7 : RUN pip install --trusted-host pypi.python.org -r requirements.txt
---> Using cache
---> b95f02b14f78
Step 5/7 : EXPOSE 80
---> Using cache
---> 0924dbc3f695
Step 6/7 : ENV NAME World
---> Using cache
---> 85c145785b87
Step 7/7 : CMD ["python", "app.py"]
---> Using cache
---> c2e43b7f0d4a
Successfully built c2e43b7f0d4a
Successfully tagged friendlyhello:latest
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.
I had similar problems with environment variables during the initial installation, and followed some advice that said to install the Windows DockerCE and hack the environment variables rather than installing the Ubuntu DockerCE, because (I hope I remembered this correctly) that WSL does not fully implement systemctl. Once the Windows Docker CE installation is done and environment variables are set, docker then works fine under WSL/Ubuntu.
An elegant way is building an array on the fly and using in_array()
:
if (in_array($var, array("abc", "def", "ghi")))
The switch
statement is also an alternative:
switch ($var) {
case "abc":
case "def":
case "hij":
echo "yes";
break;
default:
echo "no";
}
You don't have sufficient permissions to write to the root directory. See the leading slash on the filename?
The bind
method creates a new function from another function with one or more arguments bound to specific values, including the implicit this
argument.
This is an example of partial application. Normally we supply a function with all of its arguments which yields a value. This is known as function application. We are applying the function to its arguments.
Partial application is an example of a higher order function (HOF) because it yields a new function with a fewer number of argument.
You can use bind
to transform functions with multiple arguments into new functions.
function multiply(x, y) { _x000D_
return x * y; _x000D_
}_x000D_
_x000D_
let multiplyBy10 = multiply.bind(null, 10);_x000D_
console.log(multiplyBy10(5));
_x000D_
In the most common use case, when called with one argument the bind
method will create a new function that has the this
value bound to a specific value. In effect this transforms an instance method to a static method.
function Multiplier(factor) { _x000D_
this.factor = factor;_x000D_
}_x000D_
_x000D_
Multiplier.prototype.multiply = function(x) { _x000D_
return this.factor * x; _x000D_
}_x000D_
_x000D_
function ApplyFunction(func, value) {_x000D_
return func(value);_x000D_
}_x000D_
_x000D_
var mul = new Multiplier(5);_x000D_
_x000D_
// Produces garbage (NaN) because multiplying "undefined" by 10_x000D_
console.log(ApplyFunction(mul.multiply, 10));_x000D_
_x000D_
// Produces expected result: 50_x000D_
console.log(ApplyFunction(mul.multiply.bind(mul), 10));
_x000D_
The following example shows how using binding of this
can enable an object method to act as a callback that can easily update the state of an object.
function ButtonPressedLogger()_x000D_
{_x000D_
this.count = 0;_x000D_
this.onPressed = function() {_x000D_
this.count++;_x000D_
console.log("pressed a button " + this.count + " times");_x000D_
}_x000D_
for (let d of document.getElementsByTagName("button"))_x000D_
d.onclick = this.onPressed.bind(this);_x000D_
}_x000D_
_x000D_
new ButtonPressedLogger();
_x000D_
<button>press me</button>_x000D_
<button>no press me</button>
_x000D_
100 characters.
This is the var (variable) in varchar
: you only store what you enter (and an extra 2 bytes to store length upto 65535)
If it was char(200)
then you'd always store 200 characters, padded with 100 spaces
See the docs: "The CHAR and VARCHAR Types"
The problem for me turned out to be pretty obscure. My class looked like this:
//-----------------------------------------
// libbase.h
class base {
public:
base() { }
virtual ~base() { }
virtual int foo() { return 0; }
};
//-----------------------------------------
//-----------------------------------------
// libbase.cpp
#include "libbase.h"
//-----------------------------------------
//-----------------------------------------
// main.h
class derived : public base {
public:
virtual int foo() ;
};
//-----------------------------------------
//-----------------------------------------
// main.cpp
int main () {
derived d;
}
//-----------------------------------------
The problem is in the linker. My header file went in a library somewhere, but all the virtual functions were declared 'inline' in the class declaration. Since there was no code using the virtual functions (yet), the compiler or linker neglected to put actual function bodies in place. It also failed to create the vtable.
In my main code where I derived from this class, the linker tried to connect my class to the base class and his vtable. But the vtable had been discarded.
The solution was to declare at least one of the virtual functions' bodies outside the class declaration, like this:
//-----------------------------------------
// libbase.h
class base {
public:
base() { }
virtual ~base() ; //-- No longer declared 'inline'
virtual int foo() { return 0; }
};
//-----------------------------------------
//-----------------------------------------
// libbase.cpp
#include "libbase.h"
base::~base()
{
}
//-----------------------------------------
I had to add parseInt()
to tell v-for it was looking at a number.
<li v-for="n in parseInt(count)" :key="n">{{n}}</li>
To see the most recent stash:
git stash show -p
To see an arbitrary stash:
git stash show -p stash@{1}
Also, I use git diff to compare the stash with any branch.
You can use:
git diff stash@{0} master
To see all changes compared to branch master.
Or You can use:
git diff --name-only stash@{0} master
To easy find only changed file names.
EntityFunctions
is obsolete. Consider using DbFunctions
instead.
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
.Where(x => DbFunctions.TruncateTime(x.DateTimeStart) == currentDate.Date);
There are two issues:
To get the coordinates you don't need the Internet. GPS is satellite-based. But to derive street/city information from the coordinates, you'd need either to implement the map and the corresponding algorithms yourself on the device (a lot of work!) or to rely on proven services, e.g. by Google, in which case you'd need an Internet connection.
As of recently, Google allows for caching the maps, which would at least allow you to show your current position on the map even without a data connection, provided, you had cached the map in advance, when you could access the Internet.
Since this appeared to be a breaking change introduced in version 10 of pip, I downgraded to a compatible version:
pip install 'pip<10'
This command tells pip to install a version of the module lower than version 10. Do this in a virutalenv so you don't screw up your site installation of Python.
Unlike traditional RBDMs, mongoDB doesn't allow you to define any random field as the primary key, the _id field MUST exist for all standard documents.
For this reason, it doesn't make sense to create a separate uuid field.
In mongoose, the ObjectId type is used not to create a new uuid, rather it is mostly used to reference other documents.
Here is an example:
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var Schema_Product = new Schema({
categoryId : ObjectId, // a product references a category _id with type ObjectId
title : String,
price : Number
});
As you can see, it wouldn't make much sense to populate categoryId with a ObjectId.
However, if you do want a nicely named uuid field, mongoose provides virtual properties that allow you to proxy (reference) a field.
Check it out:
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var Schema_Category = new Schema({
title : String,
sortIndex : String
});
Schema_Category.virtual('categoryId').get(function() {
return this._id;
});
So now, whenever you call category.categoryId, mongoose just returns the _id instead.
You can also create a "set" method so that you can set virtual properties, check out this link for more info
See the following snippet, is this what you want?
body {
background: silver;
padding: 0 10px;
}
#content:after {
height: 10px;
display: block;
width: 100px;
background: #808080;
border-right: 1px white;
content: '';
}
#footer:before {
display: block;
content: '';
background: silver;
height: 10px;
margin-top: -20px;
margin-left: 101px;
}
#content {
background: white;
}
#footer {
padding-top: 10px;
background: #404040;
}
p {
padding: 100px;
text-align: center;
}
#footer p {
color: white;
}
_x000D_
<body>
<div id="content"><p>#content</p></div>
<div id="footer"><p>#footer</p></div>
</body>
_x000D_
In case you're on a *nix-system, have access to sed
and there can be one or more unwanted commas only in a specific field of your CSV, you can use the following one-liner in order to enclose them in "
as RFC4180 Section 2 proposes:
sed -r 's/([^,]*,[^,]*,[^,]*,)(.*)(,.*,.*)/\1"\2"\3/' inputfile
Depending on which field the unwanted comma(s) may be in you have to alter/extend the capturing groups of the regex (and the substitution).
The example above will enclose the fourth field (out of six) in quotation marks.
In combination with the --in-place
-option you can apply these changes directly to the file.
In order to "build" the right regex, there's a simple principle to follow:
[^,]*,
and put them all together in a capturing group.(.*)
.,.*
and put them all together in a capturing group.Here is a short overview of different possible regexes/substitutions depending on the specific field. If not given, the substitution is \1"\2"\3
.
([^,]*)(,.*) #first field, regex
"\1"\2 #first field, substitution
(.*,)([^,]*) #last field, regex
\1"\2" #last field, substitution
([^,]*,)(.*)(,.*,.*,.*) #second field (out of five fields)
([^,]*,[^,]*,)(.*)(,.*) #third field (out of four fields)
([^,]*,[^,]*,[^,]*,)(.*)(,.*,.*) #fourth field (out of six fields)
If you want to remove the unwanted comma(s) with sed
instead of enclosing them with quotation marks refer to this answer.
Cygwin has fully featured fork() on Windows. Thus if using Cygwin is acceptable for you, then the problem is solved in the case performance is not an issue.
Otherwise you can take a look at how Cygwin implements fork(). From a quite old Cygwin's architecture doc:
5.6. Process Creation The fork call in Cygwin is particularly interesting because it does not map well on top of the Win32 API. This makes it very difficult to implement correctly. Currently, the Cygwin fork is a non-copy-on-write implementation similar to what was present in early flavors of UNIX.
The first thing that happens when a parent process forks a child process is that the parent initializes a space in the Cygwin process table for the child. It then creates a suspended child process using the Win32 CreateProcess call. Next, the parent process calls setjmp to save its own context and sets a pointer to this in a Cygwin shared memory area (shared among all Cygwin tasks). It then fills in the child's .data and .bss sections by copying from its own address space into the suspended child's address space. After the child's address space is initialized, the child is run while the parent waits on a mutex. The child discovers it has been forked and longjumps using the saved jump buffer. The child then sets the mutex the parent is waiting on and blocks on another mutex. This is the signal for the parent to copy its stack and heap into the child, after which it releases the mutex the child is waiting on and returns from the fork call. Finally, the child wakes from blocking on the last mutex, recreates any memory-mapped areas passed to it via the shared area, and returns from fork itself.
While we have some ideas as to how to speed up our fork implementation by reducing the number of context switches between the parent and child process, fork will almost certainly always be inefficient under Win32. Fortunately, in most circumstances the spawn family of calls provided by Cygwin can be substituted for a fork/exec pair with only a little effort. These calls map cleanly on top of the Win32 API. As a result, they are much more efficient. Changing the compiler's driver program to call spawn instead of fork was a trivial change and increased compilation speeds by twenty to thirty percent in our tests.
However, spawn and exec present their own set of difficulties. Because there is no way to do an actual exec under Win32, Cygwin has to invent its own Process IDs (PIDs). As a result, when a process performs multiple exec calls, there will be multiple Windows PIDs associated with a single Cygwin PID. In some cases, stubs of each of these Win32 processes may linger, waiting for their exec'd Cygwin process to exit.
Sounds like a lot of work, doesn't it? And yes, it is slooooow.
EDIT: the doc is outdated, please see this excellent answer for an update
//new way using this and new_x000D_
function Persons(name) {_x000D_
this.name = name;_x000D_
this.greeting = function() {_x000D_
alert('Hi! I\'m ' + this.name + '.');_x000D_
};_x000D_
}_x000D_
_x000D_
var gee=new Persons("gee");_x000D_
gee.greeting();_x000D_
_x000D_
var gray=new Persons("gray");_x000D_
gray.greeting();_x000D_
_x000D_
//old way_x000D_
function createPerson(name){_x000D_
var obj={};_x000D_
obj.name=name;_x000D_
obj.greeting = function(){_x000D_
console.log("hello I am"+obj.name);_x000D_
}; _x000D_
return obj;_x000D_
}_x000D_
_x000D_
var gita=createPerson('Gita');_x000D_
gita.greeting();
_x000D_
Another thing: When you have more than one spinner in your layout, you have to implement a switch selection in the onItemSlected() method to know which widget was clicked. Something like this:
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()){
case R.id.sp_alarmSelection:
//Do something
Toast.makeText(this, "Alarm Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
break;
case R.id.sp_optionSelection:
//Do another thing
Toast.makeText(this, "Option Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
break;
}
}
Here is a copy of code which works fine for me
import json
with open("test.json") as json_file:
json_data = json.load(json_file)
print(json_data)
with the data
{
"a": [1,3,"asdf",true],
"b": {
"Hello": "world"
}
}
you may want to wrap your json.load line with a try catch because invalid JSON will cause a stacktrace error message.
How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:
Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.
Are you including "stdlib.h" or "cstdlib" in this file? NULL is defined in stdlib.h/cstdlib
#include <stdlib.h>
or
#include <cstdlib> // This is preferrable for c++
The While statement will not execute until after form1 is closed - as it is outside the main message loop.
Remove it and change the first bit of code to:
private void button1_Click_1(object sender, EventArgs e)
{
if (richTextBox1.Text != null)
{
this.Visible=false;
Form2 form2 = new Form2();
form2.show();
}
else MessageBox.Show("Insert Attributes First !");
}
This is not the best way to achieve what you are looking to do though. Instead consider the Wizard design pattern.
Alternatively you could implement a custom ApplicationContext that handles the lifetime of both forms. An example to implement a splash screen is here, which should set you on the right path.
http://www.codeproject.com/KB/cs/applicationcontextsplash.aspx?display=Print
git submodule foreach --recursive git checkout .
This didn't do the trick for me but it gave me a list of files (in my case only one) that had been changed in the submodule (without me doing anything there).
So I could head over to the submodule and git status showed me that my HEAD was detached -> git checkout master, git status to see the modified file once again, git checkout >filename<, git pull and everything fine again.
for the sake of reference:
// $query->result_object() === $query->result()
// returns:
Array ( [0] => stdClass Object ( [col_A] => val_1A , [col_B] => val_1B , ... )
[0] => stdClass Object ( [col_A] => val_2A , [col_B] => val_2B , ... )
...
)
// $query->result_array() !== $query->result()
// returns:
Array ( [0] => Array ( [col_A] => val_1A , [col_B] => val_1B , ... )
[1] => Array ( [col_A] => val_2A , [col_B] => val_2B , ... )
...
)
Suppose you want to set a pop-up text box for clicking a button lets say bt whose id is button, then code using Toast will somewhat look like this:
Button bt;
bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"The text you want to display",Toast.LENGTH_LONG)
}
Warning: Unfortunately I believe most popular platforms have dropped support for comprehensions. See below for the well-supported ES6 method
You can always use something like:
[for (i of Array(7).keys()) i*i];
Running this code on Firefox:
[ 0, 1, 4, 9, 16, 25, 36 ]
This works on Firefox (it was a proposed ES7 feature), but it has been dropped from the spec. IIRC, Babel 5 with "experimental" enabled supports this.
This is your best bet as array-comprehension are used for just this purpose. You can even write a range function to go along with this:
var range = (u, l = 0) => [ for( i of Array(u - l).keys() ) i + l ]
Then you can do:
[for (i of range(5)) i*i] // 0, 1, 4, 9, 16, 25
[for (i of range(5,3)) i*i] // 9, 16, 25
A nice way to do this any of:
[...Array(7).keys()].map(i => i * i);
Array(7).fill().map((_,i) => i*i);
[...Array(7)].map((_,i) => i*i);
This will output:
[ 0, 1, 4, 9, 16, 25, 36 ]
If you are using eclipse and working on a maven project, then also the above steps work.
Right-click on your root folder.
Properties -> Java Build Path -> Libraries -> Add Library -> JUnit -> Junit 3/4
This answer is an addition to the answer of Sindre Sorhus. The major difference between npm and Bower is the way they treat recursive dependencies. Note that they can be used together in a single project.
On the npm FAQ: (archive.org link from 6 Sep 2015)
It is much harder to avoid dependency conflicts without nesting dependencies. This is fundamental to the way that npm works, and has proven to be an extremely successful approach.
On Bower homepage:
Bower is optimized for the front-end. Bower uses a flat dependency tree, requiring only one version for each package, reducing page load to a minimum.
In short, npm aims for stability. Bower aims for minimal resource load. If you draw out the dependency structure, you will see this:
npm:
project root
[node_modules] // default directory for dependencies
-> dependency A
-> dependency B
[node_modules]
-> dependency A
-> dependency C
[node_modules]
-> dependency B
[node_modules]
-> dependency A
-> dependency D
As you can see it installs some dependencies recursively. Dependency A has three installed instances!
Bower:
project root
[bower_components] // default directory for dependencies
-> dependency A
-> dependency B // needs A
-> dependency C // needs B and D
-> dependency D
Here you see that all unique dependencies are on the same level.
So, why bother using npm?
Maybe dependency B requires a different version of dependency A than dependency C. npm installs both versions of this dependency so it will work anyway, but Bower will give you a conflict because it does not like duplication (because loading the same resource on a webpage is very inefficient and costly, also it can give some serious errors). You will have to manually pick which version you want to install. This can have the effect that one of the dependencies will break, but that is something that you will need to fix anyway.
So, the common usage is Bower for the packages that you want to publish on your webpages (e.g. runtime, where you avoid duplication), and use npm for other stuff, like testing, building, optimizing, checking, etc. (e.g. development time, where duplication is of less concern).
Update for npm 3:
npm 3 still does things differently compared to Bower. It will install the dependencies globally, but only for the first version it encounters. The other versions are installed in the tree (the parent module, then node_modules).
For more information, I suggest reading the docs of npm 3
# will get you the current local (session based) state.
SHOW Variables WHERE Variable_name='foreign_key_checks';
If you didn't SET GLOBAL, only your session was affected.
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
This function do the truncate space and words parts also.(ex: Mother into Moth...)
String.prototype.truc= function (length) {
return this.length>length ? this.substring(0, length) + '…' : this;
};
usage:
"this is long length text".trunc(10);
"1234567890".trunc(5);
output:
this is lo...
12345...
BULK INSERT dbo.temp
FROM 'c:\temp\file.txt' --- path file in db server
WITH
(
ROWTERMINATOR ='\n'
)
it work for me but save as by editplus to ansi encoding for multilanguage
You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.
Also, remove the onclick="alert()"
from your submit. This is the cause for your first undefined
message.
<?php
$posted = false;
if( $_POST ) {
$posted = true;
// Database stuff here...
// $result = mysql_query( ... )
$result = $_POST['name'] == "danny"; // Dummy result
}
?>
<html>
<head></head>
<body>
<?php
if( $posted ) {
if( $result )
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
else
echo "<script type='text/javascript'>alert('failed!')</script>";
}
?>
<form action="" method="post">
Name:<input type="text" id="name" name="name"/>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
You're correct, in that example the throws
is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.
XHTML 1 specification says:
?.3. Element Minimization and Empty Element Content
Given an empty instance of an element whose content model is not
EMPTY
(for example, an empty title or paragraph) do not use the minimized form (e.g. use<p> </p>
and not<p />
).
XHTML DTD specifies script elements as:
<!-- script statements, which may include CDATA sections -->
<!ELEMENT script (#PCDATA)>
func mimeTypeForPath(path: String) -> String {
let url = NSURL(fileURLWithPath: path)
let pathExtension = url.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension! as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream"
}
You can simply use this code,
TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();
This will return 'US' if your current connected network is in the United States. This works without a SIM card even.
You can use the environment variable $HOME
for that.
All these answers date back to 2016 or earlier... There's a new web standard for this using flex-boxes
. In general floats
for these sorts of problems is now frowned upon.
HTML
<div class="image-txt-container">
<img src="https://images4.alphacoders.com/206/thumb-350-20658.jpg">
<h2>
Text here
</h2>
</div>
CSS
.image-txt-container {
display: flex;
align-items: center;
flex-direction: row;
}
Example fiddle: https://jsfiddle.net/r8zgokeb/1/
You can use middleware and virtuals. Here is an example for your updated_at
field:
ItemSchema.virtual('name').set(function (name) {
this.updated_at = Date.now;
return name;
});
I had the same problem, but managed to fix it by suppressing the 'Expect: 100-continue' header that cURL usually sends (the following is PHP code, but should work similarly with other cURL APIs):
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));
By the way, I am sending calls to the HTTP server that is included in the JDK 6 REST stuff, which has all kinds of problems. In this case, it first sends a 100 response, and then with some requests doesn't send the subsequent 200 response correctly.
The simple and basic way (guzzle6):
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$response = $client->post('http://api.com/CheckItOutNow',
['body' => json_encode(
[
'hello' => 'World'
]
)]
);
To get the response status code and the content of the body I did this:
echo '<pre>' . var_export($response->getStatusCode(), true) . '</pre>';
echo '<pre>' . var_export($response->getBody()->getContents(), true) . '</pre>';
I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.
Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None)
)
Similar to the solution listed above with Notepad, you can also open the file in Visual Studio, if you're using that. In Visual Studio, you can select "File > Advanced Save Options..."
The "Encoding:" combo box will tell you specifically which encoding is currently being used for the file. It has a lot more text encodings listed in there than Notepad does, so it's useful when dealing with various files from around the world and whatever else.
Just like Notepad, you can also change the encoding from the list of options there, and then saving the file after hitting "OK". You can also select the encoding you want through the "Save with Encoding..." option in the Save As dialog (by clicking the arrow next to the Save button).
t = "your string"
Play with the first N characters of a string with
def firstN(s, n=2):
return s[:n]
which is by default equivalent to
t[:2]
Swift 3.0 - 4.2
import Foundation
extension String {
func toDate(withFormat format: String = "yyyy-MM-dd HH:mm:ss")-> Date?{
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
dateFormatter.locale = Locale(identifier: "fa-IR")
dateFormatter.calendar = Calendar(identifier: .gregorian)
dateFormatter.dateFormat = format
let date = dateFormatter.date(from: self)
return date
}
}
extension Date {
func toString(withFormat format: String = "EEEE ? d MMMM yyyy") -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "fa-IR")
dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
dateFormatter.calendar = Calendar(identifier: .persian)
dateFormatter.dateFormat = format
let str = dateFormatter.string(from: self)
return str
}
}
For languages not specifying a memory model, you are writing code for the language and the memory model specified by the processor architecture. The processor may choose to re-order memory accesses for performance. So, if your program has data races (a data race is when it's possible for multiple cores / hyper-threads to access the same memory concurrently) then your program is not cross platform because of its dependence on the processor memory model. You may refer to the Intel or AMD software manuals to find out how the processors may re-order memory accesses.
Very importantly, locks (and concurrency semantics with locking) are typically implemented in a cross platform way... So if you are using standard locks in a multithreaded program with no data races then you don't have to worry about cross platform memory models.
Interestingly, Microsoft compilers for C++ have acquire / release semantics for volatile which is a C++ extension to deal with the lack of a memory model in C++ http://msdn.microsoft.com/en-us/library/12a04hfd(v=vs.80).aspx. However, given that Windows runs on x86 / x64 only, that's not saying much (Intel and AMD memory models make it easy and efficient to implement acquire / release semantics in a language).
Yes, you can input multiple items from cin
, using exactly the syntax you describe. The result is essentially identical to:
cin >> a;
cin >> b;
cin >> c;
This is due to a technique called "operator chaining".
Each call to operator>>(istream&, T)
(where T
is some arbitrary type) returns a reference to its first argument. So cin >> a
returns cin
, which can be used as (cin>>a)>>b
and so forth.
Note that each call to operator>>(istream&, T)
first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.
Late to the party but ...
I'm new to python and come from a lisp background. This is what I came up with (check out the var names for lulz):
def flatten(lst):
if lst:
car,*cdr=lst
if isinstance(car,(list,tuple)):
if cdr: return flatten(car) + flatten(cdr)
return flatten(car)
if cdr: return [car] + flatten(cdr)
return [car]
Seems to work. Test:
flatten((1,2,3,(4,5,6,(7,8,(((1,2)))))))
returns:
[1, 2, 3, 4, 5, 6, 7, 8, 1, 2]
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**"); // #3
}
Ignore any request that starts with "/resources/". This is similar to configuring http@security=none when using the XML namespace configuration.
For others who came here via google like me - here's another approach:
css:
.disabled {
color: grey; // ...whatever
}
jQuery:
$('#myLink').click(function (e) {
e.preventDefault();
if ($(this).hasClass('disabled'))
return false; // Do something else in here if required
else
window.location.href = $(this).attr('href');
});
// Elsewhere in your code
if (disabledCondition == true)
$('#myLink').addClass('disabled')
else
$('#myLink').removeClass('disabled')
Remember: not only this is a css class
class="buttonstyle"
but also these two
class="buttonstyle disabled"
so you can easily add and remove further classes with jQuery. No need to touch href...
I love jQuery! ;-)
Do you really want to simply push your local repository (with its local branches, etc.) to the new remote or do you really want to mirror the old remote (with all its branches, tags, etc) on the new remote? If the latter here's a great blog on How to properly mirror a git repository.
I strongly encourage you to read the blog for some very important details, but the short version is this:
In a new directory run these commands:
git clone --mirror [email protected]/upstream-repository.git
cd upstream-repository.git
git push --mirror [email protected]/new-location.git
Try:
sudo apt-get install php-curl
It worked on a fresh Ubuntu 16.04 (Xenial Xerus) LTS, with lamp-server and php7. I tried with php7-curl
- it didn't work and also didn't work with php5-curl
.
The "parameter is not valid" exception thrown by Image.FromStream()
tells you that the stream is not a 'valid' or 'recognised' format. Watch the memory streams, especially if you are taking various offsets of bytes from a file.
// 1. Create a junk memory stream, pass it to Image.FromStream and
// get the "parameter is not valid":
MemoryStream ms = new MemoryStream(new Byte[] {0x00, 0x01, 0x02});
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);`
// 2. Create a junk memory stream, pass it to Image.FromStream
// without verification:
MemoryStream ms = new MemoryStream(new Byte[] {0x00, 0x01, 0x02});
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms, false, true);
Example 2 will work, note that useEmbeddedColorManagement must be false for validateImageData to be valid.
May be easiest to debug by dumping the memory stream to a file and inspecting the content.
A module is a single file (or files) that are imported under one import and used. e.g.
import my_module
A package is a collection of modules in directories that give a package hierarchy.
from my_package.timing.danger.internets import function_of_love
This is to keep requesting inputs while this input is integer and find whether it is odd or even else it will end.
int counter = 1;
System.out.println("Enter a number:");
Scanner OddInput = new Scanner(System.in);
while(OddInput.hasNextInt()){
int Num = OddInput.nextInt();
if (Num %2==0){
System.out.println("Number " + Num + " is Even");
System.out.println("Enter a number:");
}
else {
System.out.println("Number " + Num + " is Odd");
System.out.println("Enter a number:");
}
}
System.out.println("Program Ended");
}
Okay adding to @null's awesome post about using the Asset Catalog.
You may need to do the following to get the App's Icon linked and working for Ad-Hoc distributions / production to be seen in Organiser, Test flight and possibly unknown AppStore locations.
After creating the Asset Catalog, take note of the name of the Launch Images and App Icon names listed in the .xassets
in Xcode.
By Default this should be
AppIcon
LaunchImage
[To see this click on your .xassets folder/icon in Xcode.] (this can be changed, so just take note of this variable for later)
What is created now each build is the following data structures in your .app:
For App Icons:
iPhone
AppIcon57x57.png
(iPhone non retina) [Notice the Icon name prefix][email protected]
(iPhone retina)And the same format for each of the other icon resolutions.
iPad
AppIcon72x72~ipad.png
(iPad non retina) AppIcon72x72@2x~ipad.png
(iPad retina)(For iPad it is slightly different postfix)
Main Problem
Now I noticed that in my Info.plist
in Xcode 5.0.1 it automatically attempted and failed to create a key for "Icon files (iOS 5)
" after completing the creation of the Asset Catalog.
If it did create a reference successfully / this may have been patched by Apple or just worked, then all you have to do is review the image names to validate the format listed above.
Final Solution:
Add the following key to you main .plist
I suggest you open your main .plist
with a external text editor such as TextWrangler rather than in Xcode to copy and paste the following key in.
<key>CFBundleIcons</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon57x57.png</string>
<string>[email protected]</string>
<string>AppIcon72x72~ipad.png</string>
<string>AppIcon72x72@2x~ipad.png</string>
</array>
</dict>
</dict>
Please Note I have only included my example resolutions, you will need to add them all.
If you want to add this Key in Xcode without an external editor, Use the following:
Icon files (iOS 5)
- DictionaryPrimary Icon
- DictionaryIcon files
- ArrayItem 0
- String = AppIcon57x57.png
And for each other item / app icon.Now when you finally archive your project the final .xcarchive payload .plist will now include the above stated icon locations to build and use.
<key>IconPaths</key>
<array>
<string>Applications/Example.app/AppIcon57x57.png</string>
<string>Applications/Example.app/[email protected]</string>
<string>Applications/Example.app/AppIcon72x72~ipad.png</string>
<string>Applications/Example.app/AppIcon72x72@2x~ipad.png</string>
</array>
One thing to note is that not all libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy:
import math
import numpy
import scipy
import sympy
print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
print(math.pi == sympy.pi)
> False
As others have noted, in general use the -v
flag for the gem install
command.
If you're developing a gem locally, after cutting a gem from your gemspec:
$ gem install gemname-version.gem
Assuming version 0.8, it would look like this:
$ gem install gemname-0.8.gem
var tablefirstcolumn=$("tr").find("td:first")
alert(tablefirstcolumn+"of Each row")
Try this:
public string EncodeBase64(string data)
{
string s = data.Trim().Replace(" ", "+");
if (s.Length % 4 > 0)
s = s.PadRight(s.Length + 4 - s.Length % 4, '=');
return Encoding.UTF8.GetString(Convert.FromBase64String(s));
}
You could do something like this for your case - (syntax may be a bit off). Also look at this link
subQuery = (from crtu in CompanyRolesToUsers where crtu.RoleId==2 || crtu.RoleId==3 select crtu.UserId).ToArrayList();
finalQuery = from u in Users where u.LastName.Contains('fra') && subQuery.Contains(u.Id) select u;
Use ::ng-deep with caution. I used it throughout my app to set the material design toolbar color to different colors throughout my app only to find that when the app was in testing the toolbar colors step on each other. Come to find out it is because these styles becomes global, see this article Here is a working code solution that doesn't bleed into other components.
<mat-toolbar #subbar>
...
</mat-toolbar>
export class BypartSubBarComponent implements AfterViewInit {
@ViewChild('subbar', { static: false }) subbar: MatToolbar;
constructor(
private renderer: Renderer2) { }
ngAfterViewInit() {
this.renderer.setStyle(
this.subbar._elementRef.nativeElement, 'backgroundColor', 'red');
}
}
In actionPerformed(ActionEvent e)
you call encrypt()
, which is declared to throw Exception
. However, actionPerformed
neither catches this Exception (with try/catch around the call to encrypt()
) nor declares that it throws Exception
itself.
Your encrypt
method, however, does not truly throw Exception
. It swallows all Exceptions without even as much as logging a complaint. (Bad practice and bad style!)
Also, your encrypt
method does the following:
public static byte[] encrypt(String toEncrypt) throws Exception {
try{
....
return encrypted; // HERE YOU CORRECTLY RETURN A VALUE
} catch(Exception e) {
}
// YOU DO NOT RETURN ANYTHING HERE
}
That is, if you do catch any Exception, you discard it silently and then fall off the bottom of your encrypt
method without actually returning anything. This won't compile (as you see), because a method that is declared to return a value must either return a value or throw an Exception for every single possible code path.
use jquery:
<select class="target">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<script>
$('.target').change(function() { doSomething(); });
</script>
I think you might be looking for Except
:
The Except operator produces the set difference between two sequences. It will only return elements in the first sequence that don't appear in the second. You can optionally provide your own equality comparison function.
Check out this link, this link, or Google, for more information.
You can also use array_reduce()
if you prefer a more functional approach
For instance:
$userNames = array_reduce($users, function ($carry, $user) {
array_push($carry, $user['name']);
return $carry;
}, []);
Or if you like to be fancy,
$userNames = [];
array_map(function ($user) use (&$userNames){
$userNames[]=$user['name'];
}, $users);
This and all the methods above do loop behind the scenes though ;)
You need a regular expression for this. Look here. If you are using .net Framework4.5 then you can also use this. As it is built in .net Framework 4.5. Example
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
you can use setSeconds
method by getting seconds from today and just adding 10 seconds in it
var today = new Date();
today.setSeconds(today.getSeconds() + 10);
You can add 10 *1000 milliseconds to the new date:
var today = new Date();
today = new Date(today.getTime() + 1000*10);
You can use setTime
:
today.setTime(now.getTime() + 10000)
I used to be irked by this problem; and I used to have a macro-cum-wrapper-function solution just like in Talonmies and Jared's answers, but, honestly? It makes using the CUDA Runtime API even more ugly and C-like.
So I've approached this in a different and more fundamental way. For a sample of the result, here's part of the CUDA vectorAdd
sample - with complete error checking of every runtime API call:
// (... prepare host-side buffers here ...)
auto current_device = cuda::device::current::get();
auto d_A = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_B = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_C = cuda::memory::device::make_unique<float[]>(current_device, numElements);
cuda::memory::copy(d_A.get(), h_A.get(), size);
cuda::memory::copy(d_B.get(), h_B.get(), size);
// (... prepare a launch configuration here... )
cuda::launch(vectorAdd, launch_config,
d_A.get(), d_B.get(), d_C.get(), numElements
);
cuda::memory::copy(h_C.get(), d_C.get(), size);
// (... verify results here...)
Again - all potential errors are checked , and an exception if an error occurred (caveat: If the kernel caused some error after launch, it will be caught after the attempt to copy the result, not before; to ensure the kernel was successful you would need to check for error between the launch and the copy with a cuda::outstanding_error::ensure_none()
command).
The code above uses my
Thin Modern-C++ wrappers for the CUDA Runtime API library (Github)
Note that the exceptions carry both a string explanation and the CUDA runtime API status code after the failing call.
A few links to how CUDA errors are automagically checked with these wrappers:
Edit your env var for JAVA_HOME
to point to the new installed JDK 1.8:
R-click on My Computer -> Properties -> Advanced System Settings -> Environment Variables
find JAVA_HOME
on the list and set it's value to something like that:
C:\Program Files\Java\jdk1.8.0_31
Find the old version and edit it in PATH
variable aswell.
Should be done.
Another solution with your own message in exception.
import os
try:
os.remove(filename)
except:
print("Not able to delete the file %s" % filename)
You are right, that test
"and"s the two operands. But the result is discarded, the only thing that stays, and thats the important part, are the flags. They are set and thats the reason why the test
instruction is used (and exist).
JE
jumps not when equal (it has the meaning when the instruction before was a comparison), what it really does, it jumps when the ZF
flag is set. And as it is one of the flags that is set by test
, this instruction sequence (test x,x; je...) has the meaning that it is jumped when x is 0.
For questions like this (and for more details) I can just recommend a book about x86 instruction, e.g. even when it is really big, the Intel documentation is very good and precise.
In applied usage for the Asynchronous IO coroutine, yield from
has a similar behavior as await
in a coroutine function. Both of which is used to suspend the execution of coroutine.
yield from
is used by the generator-based coroutine.
For Asyncio, if there's no need to support an older Python version (i.e. >3.5), async def
/await
is the recommended syntax to define a coroutine. Thus yield from
is no longer needed in a coroutine.
But in general outside of asyncio, yield from <sub-generator>
has still some other usage in iterating the sub-generator as mentioned in the earlier answer.
You can also approach this in a much less smarter fashion
q=()
q+=( 1-2 )
q+=( a-b )
for set in ${q[@]};
do
echo ${set%%-*}
echo ${set##*-}
done
of course a 22 line solution or indirection is probably the better way to go and why not sprinkle eval every where to .
You may have used the filter function in the console which will hide anything that doesn't match your query. Remove the query and your messages will display.
As of PHP 7.4, this is no longer an issue. Support for caching_sha2
authentication method has been added to mysqlnd.
Currently, PHP mysqli extension do not support new caching_sha2 authentication feature. You have to wait until they release an update.
Check related post from MySQL developers: https://mysqlserverteam.com/upgrading-to-mysql-8-0-default-authentication-plugin-considerations/
They didn't mention PDO, maybe you should try to connect with PDO.
Once you opened the mongo CLI, connected and authorized on the right database.
The following example shows how to find the document with the _id=568c28fffc4be30d44d0398e from a collection called “products”:
db.products.find({"_id": ObjectId("568c28fffc4be30d44d0398e")})
On Linux Fedora30 several versions of the full java JDK are available, specifically package names:
java-1.8.0-openjdk-devel.x86_64
java-11-openjdk-devel.x86_64
Once installed, they are found in: /usr/lib/jvm
To select the location/directory of a full development JDK (which is different from the simpler runtime only JRE) look for entries:
ls -ld java*openjdk*
Here are two good choices, which are links to specific versions, where you will have to select the version:
/usr/lib/jvm/java-1.8.0-openjdk
/usr/lib/jvm/java-11-openjdk
We can compile the code of C in Sublime Text and can print some value or strings but it does not accept input from the user. (Till I know... I am sure about compiling but not about output from given input.) If you are using Windows you have to set the environment variables for Sublime Text and GCC compiler.
Well I always use the same easy way and it works for me. In your HTML keep the type as text (like this):
<input type="text" class="textfield" value="" id="onlyNumbers" name="onlyNumbers" onkeypress="return isNumber(event)" onpaste="return false;"/>
After this you only need to add a method on javascript
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ( (charCode > 31 && charCode < 48) || charCode > 57) {
return false;
}
return true;
}
</script>
With this easy validation you will only get positive numbers as you wanted. You can modify the charCodes to add more valid keys to your method.
Here´s the code working: Only numbers validation
If you need submodules as well, this should do the trick: https://github.com/meitar/git-archive-all.sh/wiki
Both rebase
(and cherry-pick
) and merge
have their advantages and disadvantages. I argue for merge
here, but it's worth understanding both. (Look here for an alternate, well-argued answer enumerating cases where rebase
is preferred.)
merge
is preferred over cherry-pick
and rebase
for a couple of reasons.
merge
workflow fairly easily. rebase
tends to be considered more advanced. It's best to understand both, but people who do not want to be experts in version control (which in my experience has included many colleagues who are damn good at what they do, but don't want to spend the extra time) have an easier time just merging.Even with a merge-heavy workflow rebase
and cherry-pick
are still useful for particular cases:
merge
is cluttered history. rebase
prevents a long series of commits from being scattered about in your history, as they would be if you periodically merged in others' changes. That is in fact its main purpose as I use it. What you want to be very careful of, is never to rebase
code that you have shared with other repositories. Once a commit is push
ed someone else might have committed on top of it, and rebasing will at best cause the kind of duplication discussed above. At worst you can end up with a very confused repository and subtle errors it will take you a long time to ferret out.cherry-pick
is useful for sampling out a small subset of changes from a topic branch you've basically decided to discard, but realized there are a couple of useful pieces on.As for preferring merging many changes over one: it's just a lot simpler. It can get very tedious to do merges of individual changesets once you start having a lot of them. The merge resolution in git (and in Mercurial, and in Bazaar) is very very good. You won't run into major problems merging even long branches most of the time. I generally merge everything all at once and only if I get a large number of conflicts do I back up and re-run the merge piecemeal. Even then I do it in large chunks. As a very real example I had a colleague who had 3 months worth of changes to merge, and got some 9000 conflicts in 250000 line code-base. What we did to fix is do the merge one month's worth at a time: conflicts do not build up linearly, and doing it in pieces results in far fewer than 9000 conflicts. It was still a lot of work, but not as much as trying to do it one commit at a time.
using the Integer data type with values 0 and 1 is the fastest.
Java lacks coalesce operator, so your code with an explicit temporary is your best choice for an assignment with a single call.
You can use the result variable as your temporary, like this:
dinner = ((dinner = cage.getChicken()) != null) ? dinner : getFreeRangeChicken();
This, however, is hard to read.
A more general answer which accepts all the special characters including _
would be slightly different:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\W|\_])(?=\S+$).{8,}$
The difference (?=.*[\W|\_])
translates to "at least one of all the special characters including the underscore".
For me
document.addEventListener("mousewheel", this.mousewheel.bind(this), { passive: false });
did the trick (the { passive: false }
part).
You have to load the db library first. In autoload.php
add :
$autoload['libraries'] = array('database');
Also, try renaming User model class for "User_model".
.switch {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
width: 90px;_x000D_
height: 34px;_x000D_
}_x000D_
_x000D_
.switch input {display:none;}_x000D_
_x000D_
.slider {_x000D_
position: absolute;_x000D_
cursor: pointer;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
background-color: #ca2222;_x000D_
-webkit-transition: .4s;_x000D_
transition: .4s;_x000D_
}_x000D_
_x000D_
.slider:before {_x000D_
position: absolute;_x000D_
content: "";_x000D_
height: 26px;_x000D_
width: 26px;_x000D_
left: 4px;_x000D_
bottom: 4px;_x000D_
background-color: white;_x000D_
-webkit-transition: .4s;_x000D_
transition: .4s;_x000D_
}_x000D_
_x000D_
input:checked + .slider {_x000D_
background-color: #2ab934;_x000D_
}_x000D_
_x000D_
input:focus + .slider {_x000D_
box-shadow: 0 0 1px #2196F3;_x000D_
}_x000D_
_x000D_
input:checked + .slider:before {_x000D_
-webkit-transform: translateX(55px);_x000D_
-ms-transform: translateX(55px);_x000D_
transform: translateX(55px);_x000D_
}_x000D_
_x000D_
/*------ ADDED CSS ---------*/_x000D_
.on_x000D_
{_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.on, .off_x000D_
{_x000D_
color: white;_x000D_
position: absolute;_x000D_
transform: translate(-50%,-50%);_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
font-size: 10px;_x000D_
font-family: Verdana, sans-serif;_x000D_
}_x000D_
_x000D_
input:checked+ .slider .on_x000D_
{display: block;}_x000D_
_x000D_
input:checked + .slider .off_x000D_
{display: none;}_x000D_
_x000D_
/*--------- END --------*/_x000D_
_x000D_
/* Rounded sliders */_x000D_
.slider.round {_x000D_
border-radius: 34px;_x000D_
}_x000D_
_x000D_
.slider.round:before {_x000D_
border-radius: 50%;}
_x000D_
<label class="switch"><input type="checkbox" id="togBtn"><div class="slider round"><!--ADDED HTML --><span class="on">Confirmed</span><span class="off">NA</span><!--END--></div></label>
_x000D_
Why don't you go for awk:
awk '/Start pattern/,/End pattern/' filename
PictureBox.Image is a property, not a method. You can set it like this:
PictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);
from: http://ruby-doc.org/core/classes/String.html#M000809
str.intern => symbol
str.to_sym => symbol
Returns the Symbol corresponding to str
, creating the symbol if it did not previously exist. See Symbol#id2name
.
"Koala".intern #=> :Koala
s = 'cat'.to_sym #=> :cat
s == :cat #=> true
s = '@cat'.to_sym #=> :@cat
s == :@cat #=> true
This can also be used to create symbols that cannot be represented using the :xxx
notation.
'cat and dog'.to_sym #=> :"cat and dog"
But for your example ...
"Book Author Title".gsub(/\s+/, "_").downcase.to_sym
should go ;)
Have you tried using the fb:// protocol?
To have them like your page when they scan the qr code, it goes like this:
fb://page/(pageID)/addfan
If you need to get the pageID, replace "www" with "graph" in the Facebook url when you visit your page in a desktop browser and it will display the ID and other data.
Not only does this add them automatically, but it opens up the page in the FB app instead of the mobile browser.
As far as legality, I would assume as long as you put something like "Scan to like our page", you're in the clear. They know what they're getting into.
Using Console.WriteLine( "Test" );
is able to write log messages to the Output Window (View Menu --> Output) in Visual Studio for a Windows Forms/WPF project.
However, I encountered a case where it was not working and only System.Diagnostics.Debug.WriteLine( "Test" );
was working. I restarted Visual Studio and Console.WriteLine()
started working again. Seems to be a Visual Studio bug.
This is not an answer to your question but I believe it is the solution to your problem. The interface org.springframework.data.repository.CrudRepository
does indeed have methods that return java.lang.Iterable
but you should not use this interface. Instead use sub interfaces, in your case org.springframework.data.mongodb.repository.MongoRepository
. This interface has methods that return objects of type java.util.List
.
I think your problem is when displaying the decimal, not the contents of it.
If you try
string value = "1200.00";
decimal d = decimal.Parse(s);
string s = d.ToString();
s
will contain the string "1200"
.
However if you change your code to this
string value = "1200.00";
decimal d = decimal.Parse(s);
string s = d.ToString("0.00");
s
will contain the string "1200.00"
as you want it to do.
EDIT
Seems I'm braindead early in the morning today. I added the Parse
statements now. However even my first code will output "1200.00", even if I expected it to output "1200". Seems like I'm learning something each day, and in this case obviously something that is quite basic.
So disregard this a an proper answer. We will probably need more code to identify your problem in this case.
Try jcabi-http
, which is a fluent Java HTTP client, for example:
String html = new JdkRequest("https://www.google.com")
.header(HttpHeaders.ACCEPT, MediaType.TEXT_HTML)
.fetch()
.as(HttpResponse.class)
.assertStatus(HttpURLConnection.HTTP_OK)
.body();
Check also this blog post: http://www.yegor256.com/2014/04/11/jcabi-http-intro.html
The best and tested solution is to put the following small snippet which will collapse the accordion tab which is already open when you load. In my case the last sixth tab was open so I made it collapsed on page load.
$(document).ready(){
$('#collapseSix').collapse("hide");
}
I don't think there is anything built-in, but you can do it by leaving more space above your axes and using figtext
:
axes([.1,.1,.8,.7])
figtext(.5,.9,'Foo Bar', fontsize=18, ha='center')
figtext(.5,.85,'Lorem ipsum dolor sit amet, consectetur adipiscing elit',fontsize=10,ha='center')
ha
is short for horizontalalignment
.
There is a GitHub project called Xcode Project Renamer
:
It should be executed from inside root of Xcode project directory and called with two string parameters: $OLD_PROJECT_NAME & $NEW_PROJECT_NAME
Script goes through all the files and directories recursively, including Xcode project or workspace file and replaces all occurrences of $OLD_PROJECT_NAME string with $NEW_PROJECT_NAME string (both in each file's name and content).
You can quickly serve static content in JAVA Spring-boot App via thymeleaf
(ref: source)
I assume you have already added Spring Boot plugin apply plugin: 'org.springframework.boot'
and the necessary buildscript
Then go ahead and ADD thymeleaf to your build.gradle
==>
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Lets assume you have added home.html at src/main/resources
To serve this file, you will need to create a controller.
package com.ajinkya.th.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomePageController {
@RequestMapping("/")
public String homePage() {
return "home";
}
}
Thats it ! Now restart your gradle server. ./gradlew bootRun