We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()
Modified erikkallen answer:
$(document).unbind('keydown').bind('keydown', function (event) {
var doPrevent = false, elem;
if (event.keyCode === 8) {
elem = event.srcElement || event.target;
if( $(elem).is(':input') ) {
doPrevent = elem.readOnly || elem.disabled;
} else {
doPrevent = true;
}
}
if (doPrevent) {
event.preventDefault();
return false;
}
});
The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
// auto-sets values on creation
static::creating(function ($query) {
$query->is_voicemail = $query->is_voicemail ?? true;
});
}
To hide the prompt set xls.DisplayAlerts = False
ConflictResolution
is not a true
or false
property, it should be xlLocalSessionChanges
Note that this has nothing to do with displaying the Overwrite prompt though!
Set xls = CreateObject("Excel.Application")
xls.DisplayAlerts = False
Set wb = xls.Workbooks.Add
fullFilePath = importFolderPath & "\" & "A.xlsx"
wb.SaveAs fullFilePath, AccessMode:=xlExclusive,ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
wb.Close (True)
For me, the easiest way was to install via ruby gem
sudo gem install cocoapods -v
Please note -v for verbose. It takes while to install cocoapods and often you get confused if it's really happening.
Use font
property of UILabel
:
label.font = UIFont(name:"HelveticaNeue-Bold", size: 16.0)
or use default system font
to bold text:
label.font = UIFont.boldSystemFont(ofSize: 16.0)
In case you enabled debugging mode
on your phone and adb devices
is not listing your device, it seems there is a problem with phone driver. You might not install the usb-driver of your phone or driver might be installed with problems (in windows check in system --> device manager).
In my case, I had the same problem with My HTC android usb device which installing drivers again, fixed my problems.
BufferedImage consists of two main classes: Raster & ColorModel. Raster itself consists of two classes, DataBufferByte for image content while the other for pixel color.
if you want the data from DataBufferByte, use:
public byte[] extractBytes (String ImageName) throws IOException {
// open image
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);
// get DataBufferBytes from Raster
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
return ( data.getData() );
}
now you can process these bytes by hiding text in lsb for example, or process it the way you want.
Sometimes i see this error in my project. I solve that by
1 - Right click on EDMX file
2 - Select Run Custom Tool
option
3 - Rebuild project
This should do:
Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName aName = assem.GetName();
return aName.Version.ToString();
They Say Use NSUserDefaults
When I was implementing long term (after app close) data storage for the first time, everything I read online pointed me towards NSUserDefaults. However, I wanted to store a dictionary and, although possible, it was proving to be a pain. I spent hours trying to get type-errors to go away.
NSUserDefaults is Also Limited in Function
Further reading revealed how the read/write of NSUserDefaults really forces the app to read/write everything or nothing, all at once, so it isn't efficient. Then I learned that retrieving an array isn't straight forward. I realized that if you're storing more than a few strings or booleans, NSUserDefaults really isn't ideal.
It's also not scalable. If you're learning how to code, learn the scalable way. Only use NSUserDefaults for storing simple strings or booleans related to preferences. Store arrays and other data using Core Data, it's not as hard as they say. Just start small.
Update: Also, if you add Apple Watch support, there's another potential consideration. Your app's NSUserDefaults is now automatically sent to the Watch Extension.
Using Core Data
So I ignored the warnings about Core Data being a more difficult solution and started reading. Within three hours I had it working. I had my table array being saved in Core Data and reloading the data upon opening the app back up! The tutorial code was easy enough to adapt and I was able to have it store both title and detail arrays with only a little extra experimenting.
So for anyone reading this post who's struggling with NSUserDefault type issues or whose need is more than storing strings, consider spending an hour or two playing with core data.
Here's the tutorial I read:
http://www.raywenderlich.com/85578/first-core-data-app-using-swift
If you didn't check "Core Data"
If you didn't check "Core Data"when you created your app, you can add it after and it only takes five minutes:
http://craig24.com/2014/12/how-to-add-core-data-to-an-existing-swift-project-in-xcode/
http://blog.zeityer.com/post/119012600864/adding-core-data-to-an-existing-swift-project
How to Delete from Core Data Lists
Not sure I agree, If I want to test 'File Upload' and then test 'Data Inserted by File Upload' why would I not want these to be independent from each other? Perfectly reasonable I think to be able to run them separately rather than having both in a Goliath test case.
I use this to cause 60 events per hour with most events occurring at the same number of seconds after the whole minute:
import math
import time
import random
TICK = 60 # one minute tick size
TICK_TIMING = 59 # execute on 59th second of the tick
TICK_MINIMUM = 30 # minimum catch up tick size when lagging
def set_timing():
now = time.time()
elapsed = now - info['begin']
minutes = math.floor(elapsed/TICK)
tick_elapsed = now - info['completion_time']
if (info['tick']+1) > minutes:
wait = max(0,(TICK_TIMING-(time.time() % TICK)))
print ('standard wait: %.2f' % wait)
time.sleep(wait)
elif tick_elapsed < TICK_MINIMUM:
wait = TICK_MINIMUM-tick_elapsed
print ('minimum wait: %.2f' % wait)
time.sleep(wait)
else:
print ('skip set_timing(); no wait')
drift = ((time.time() - info['begin']) - info['tick']*TICK -
TICK_TIMING + info['begin']%TICK)
print ('drift: %.6f' % drift)
info['tick'] = 0
info['begin'] = time.time()
info['completion_time'] = info['begin'] - TICK
while 1:
set_timing()
print('hello world')
#random real world event
time.sleep(random.random()*TICK_MINIMUM)
info['tick'] += 1
info['completion_time'] = time.time()
Depending upon actual conditions you might get ticks of length:
60,60,62,58,60,60,120,30,30,60,60,60,60,60...etc.
but at the end of 60 minutes you'll have 60 ticks; and most of them will occur at the correct offset to the minute you prefer.
On my system I get typical drift of < 1/20th of a second until need for correction arises.
The advantage of this method is resolution of clock drift; which can cause issues if you're doing things like appending one item per tick and you expect 60 items appended per hour. Failure to account for drift can cause secondary indications like moving averages to consider data too deep into the past resulting in faulty output.
Well, technically speaking we can pass a parameter to a computed function, the same way we can pass a parameter to a getter function in vuex. Such a function is a function that returns a function.
For instance, in the getters of a store:
{
itemById: function(state) {
return (id) => state.itemPool[id];
}
}
This getter can be mapped to the computed functions of a component:
computed: {
...mapGetters([
'ids',
'itemById'
])
}
And we can use this computed function in our template as follows:
<div v-for="id in ids" :key="id">{{itemById(id).description}}</div>
We can apply the same approach to create a computed method that takes a parameter.
computed: {
...mapGetters([
'ids',
'itemById'
]),
descriptionById: function() {
return (id) => this.itemById(id).description;
}
}
And use it in our template:
<div v-for="id in ids" :key="id">{{descriptionById(id)}}</div>
This being said, I'm not saying here that it's the right way of doing things with Vue.
However, I could observe that when the item with the specified ID is mutated in the store, the view does refresh its contents automatically with the new properties of this item (the binding seems to be working just fine).
The most common cause for this issue is Xcode 6.3 and running iOS 8.2 on your device. Xcode 6.3 doesn't install the 8.2 simulator by default. It has the 8.3 simulator installed.
The solution by @joshstaiger works, but it is not a permanent fix. You have to do this each time you want to run the app on your device
The permanent fix is to simply install the 8.2 simulator in Xcode 6.3. Go the Xcode -> Preferences -> Downloads. Install the 8.2 simulator under Components.
Now you will no longer see your device listed under ineligible devices.
Since GDB 7.5 you can use these native Convenience Functions:
$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)
Seems quite less problematic than having to execute a "foreign" strcmp()
on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.
Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running
show configuration
inside GDB and searching for--with-python
. This little oneliner does the trick, too:$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python' --with-python=/usr (relocatable)
For your demo case, the usage would be
break <where> if $_streq(x, "hello")
or, if your breakpoint already exists and you just want to add the condition to it
condition <breakpoint number> $_streq(x, "hello")
$_streq
only matches the whole string, so if you want something more cunning you should use $_regex
, which supports the Python regular expression syntax.
Your question is not particularly clear, but in case you want to send POST data to a url without using a form, you can use either fsockopen or curl.
There could be many reason why document.getElementById
doesn't work
You have an invalid ID
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (resource: What are valid values for the id attribute in HTML?)
you used some id that you already used as <meta>
name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at
(resource: http://www.phpied.com/getelementbyid-description-in-ie/)
you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument
before looking for the element
(resource: Calling a specific id inside a frame)
you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling
I doubt you used same ID twice or more: in that case document.getElementById
should return at least the first element
"user": {
"firstName": "Musa",
"lastName": "Aliyev",
"email": "[email protected]",
"passwordIn": "98989898", (or encoded version in front if we not using https)
"country": "Azeribaijan",
"phone": "+994707702747"
}
@CrossOrigin(methods=RequestMethod.POST)
@RequestMapping("/public/register")
public @ResponseBody MsgKit registerNewUsert(@RequestBody User u){
root.registerUser(u);
return new MsgKit("registered");
}
@Service
@Transactional
public class RootBsn {
@Autowired UserRepository userRepo;
public void registerUser(User u) throws Exception{
u.setPassword(u.getPasswordIn());
//Generate some salt and setPassword (encoded - salt+password)
User u=userRepo.save(u);
System.out.println("Registration information saved");
}
}
@Entity
@JsonIgnoreProperties({"recordDate","modificationDate","status","createdBy","modifiedBy","salt","password"})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String country;
@Column(name="CREATED_BY")
private String createdBy;
private String email;
@Column(name="FIRST_NAME")
private String firstName;
@Column(name="LAST_LOGIN_DATE")
private Timestamp lastLoginDate;
@Column(name="LAST_NAME")
private String lastName;
@Column(name="MODIFICATION_DATE")
private Timestamp modificationDate;
@Column(name="MODIFIED_BY")
private String modifiedBy;
private String password;
@Transient
private String passwordIn;
private String phone;
@Column(name="RECORD_DATE")
private Timestamp recordDate;
private String salt;
private String status;
@Column(name="USER_STATUS")
private String userStatus;
public User() {
}
// getters and setters
}
This way you will be able to send ZPL to a printer no matter how it is connected (LPT, USB, Network Share...)
Create the RawPrinterHelper class (from the Microsoft article on How to send raw data to a printer by using Visual C# .NET):
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class RawPrinterHelper
{
// Structure and API declarions:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)] public string pDocName;
[MarshalAs(UnmanagedType.LPStr)] public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)] public string pDataType;
}
[DllImport("winspool.Drv", EntryPoint="OpenPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
[DllImport("winspool.Drv", EntryPoint="ClosePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="StartDocPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool StartDocPrinter( IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
[DllImport("winspool.Drv", EntryPoint="EndDocPrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="StartPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="EndPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="WritePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten );
// SendBytesToPrinter()
// When the function is given a printer name and an unmanaged array
// of bytes, the function sends those bytes to the print queue.
// Returns true on success, false on failure.
public static bool SendBytesToPrinter( string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
Int32 dwError = 0, dwWritten = 0;
IntPtr hPrinter = new IntPtr(0);
DOCINFOA di = new DOCINFOA();
bool bSuccess = false; // Assume failure unless you specifically succeed.
di.pDocName = "My C#.NET RAW Document";
di.pDataType = "RAW";
// Open the printer.
if( OpenPrinter( szPrinterName.Normalize(), out hPrinter, IntPtr.Zero ) )
{
// Start a document.
if( StartDocPrinter(hPrinter, 1, di) )
{
// Start a page.
if( StartPagePrinter(hPrinter) )
{
// Write your bytes.
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
}
// If you did not succeed, GetLastError may give more information
// about why not.
if( bSuccess == false )
{
dwError = Marshal.GetLastWin32Error();
}
return bSuccess;
}
public static bool SendFileToPrinter( string szPrinterName, string szFileName )
{
// Open the file.
FileStream fs = new FileStream(szFileName, FileMode.Open);
// Create a BinaryReader on the file.
BinaryReader br = new BinaryReader(fs);
// Dim an array of bytes big enough to hold the file's contents.
Byte []bytes = new Byte[fs.Length];
bool bSuccess = false;
// Your unmanaged pointer.
IntPtr pUnmanagedBytes = new IntPtr(0);
int nLength;
nLength = Convert.ToInt32(fs.Length);
// Read the contents of the file into the array.
bytes = br.ReadBytes( nLength );
// Allocate some unmanaged memory for those bytes.
pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
// Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
// Send the unmanaged bytes to the printer.
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
// Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes);
return bSuccess;
}
public static bool SendStringToPrinter( string szPrinterName, string szString )
{
IntPtr pBytes;
Int32 dwCount;
// How many characters are in the string?
dwCount = szString.Length;
// Assume that the printer is expecting ANSI text, and then convert
// the string to ANSI text.
pBytes = Marshal.StringToCoTaskMemAnsi(szString);
// Send the converted ANSI string to the printer.
SendBytesToPrinter(szPrinterName, pBytes, dwCount);
Marshal.FreeCoTaskMem(pBytes);
return true;
}
}
Call the print method:
private void BtnPrint_Click(object sender, System.EventArgs e)
{
string s = "^XA^LH30,30\n^FO20,10^ADN,90,50^AD^FDHello World^FS\n^XZ";
PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new PrinterSettings();
if(DialogResult.OK == pd.ShowDialog(this))
{
RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, s);
}
}
There are 2 gotchas I've come across that happen when you're sending txt files with ZPL codes to the printer:
Encoding has to be set to Encoding.Default when reading ANSI txt files with special characters
public static bool SendTextFileToPrinter(string szFileName, string printerName)
{
var sb = new StringBuilder();
using (var sr = new StreamReader(szFileName, Encoding.Default))
{
while (!sr.EndOfStream)
{
sb.AppendLine(sr.ReadLine());
}
}
return RawPrinterHelper.SendStringToPrinter(printerName, sb.ToString());
}
Try giving your Button in your main.xml a more descriptive name such as:
<Button
android:id="@+id/buttonXYZ"
(use lowercase in your xml files, at least, the first letter)
And then in your MainActivity class, declare it as:
Button buttonXYZ;
In your onCreate(Bundle savedInstanceState) method, define it as:
buttonXYZ = (Button) findViewById(R.id.buttonXYZ);
Also, move the Buttons/TextViews outside and place them before the .setOnClickListener - it makes the code cleaner.
Username = (EditText)findViewById(R.id.Username);
CompanyID = (EditText)findViewById(R.id.CompanyID);
I like Tatarize's answer, but I'll provide an alternative. This is a trivial linear algebra problem, and the method I present works well with pan, zoom, skew, etc. That is, it works well if your image is already transformed.
When a matrix is scaled, the scale is at point (0, 0). So, if you have an image and scale it by a factor of 2, the bottom-right point will double in both the x and y directions (using the convention that [0, 0] is the top-left of the image).
If instead you would like to zoom the image about the center, then a solution is as follows: (1) translate the image such that its center is at (0, 0); (2) scale the image by x and y factors; (3) translate the image back. i.e.
myMatrix
.translate(image.width / 2, image.height / 2) // 3
.scale(xFactor, yFactor) // 2
.translate(-image.width / 2, -image.height / 2); // 1
More abstractly, the same strategy works for any point. If, for example, you want to scale the image at a point P:
myMatrix
.translate(P.x, P.y)
.scale(xFactor, yFactor)
.translate(-P.x, -P.y);
And lastly, if the image is already transformed in some manner (for example, if it's rotated, skewed, translated, or scaled), then the current transformation needs to be preserved. Specifically, the transform defined above needs to be post-multiplied (or right-multiplied) by the current transform.
myMatrix
.translate(P.x, P.y)
.scale(xFactor, yFactor)
.translate(-P.x, -P.y)
.multiply(myMatrix);
There you have it. Here's a plunk that shows this in action. Scroll with the mousewheel on the dots and you'll see that they consistently stay put. (Tested in Chrome only.) http://plnkr.co/edit/3aqsWHPLlSXJ9JCcJzgH?p=preview
A peculiar difference I have noted on gcc 5.2.1 and clang 3.6.2 is that if you have a critical loop like:
for (;;) {
if (!visited) {
....
}
node++;
if (!*node) break;
}
Then gcc will, when compiling with -O3
or -O2
, speculatively
unroll the loop eight times. Clang will not unroll it at all. Through
trial and error I found that in my specific case with my program data,
the right amount of unrolling is five so gcc overshot and clang
undershot. However, overshooting was more detrimental to performance, so
gcc performed much worse here.
I have no idea if the unrolling difference is a general trend or just something that was specific to my scenario.
A while back I wrote a few garbage collectors to teach myself more about performance optimization in C. And the results I got is in my mind enough to slightly favor clang. Especially since garbage collection is mostly about pointer chasing and copying memory.
The results are (numbers in seconds):
+---------------------+-----+-----+
|Type |GCC |Clang|
+---------------------+-----+-----+
|Copying GC |22.46|22.55|
|Copying GC, optimized|22.01|20.22|
|Mark & Sweep | 8.72| 8.38|
|Ref Counting/Cycles |15.14|14.49|
|Ref Counting/Plain | 9.94| 9.32|
+---------------------+-----+-----+
This is all pure C code, and I make no claim about either compiler's performance when compiling C++ code.
On Ubuntu 15.10, x86.64, and an AMD Phenom(tm) II X6 1090T processor.
Yes easy.
wget --spider www.bluespark.co.nz
That will give you
Resolving www.bluespark.co.nz... 210.48.79.121
Connecting to www.bluespark.co.nz[210.48.79.121]:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
200 OK
The above answers are wrong, respectively aren't answering why you're having troubles viewing the demo-content prod-mode.
Here's the correct answer: clear your "prod"-cache:
php app/console cache:clear --env prod
Sure.
.orElseThrow(() -> new MyException(someArgument))
Try this code:
For Each aSheet In Worksheets
Select Case aSheet.Name
Case "ID Sheet", "Summary"
Application.DisplayAlerts = False
aSheet.Delete
Application.DisplayAlerts = True
End Select
Next aSheet
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
<select name='partyid' id="partyid" class='span3'>
<option value=''>Select Party</option>
<option ng-repeat="item in partyName" value="{{item._id}}" ng-selected="obj.partyname == item.partyname">{{item.partyname}}
</option>
</select>
MOST EFFECTIVE WAY!
public static void main(String args[])
{
int [] array = new int[10];//creates an array named array to hold 10 int's
for(int x: array)//for-each loop!
x = ((int)(Math.random()*100+1));
Array.sort(array);
for(int x: array)
System.out.println(x+" ");
}
In the case where the process was spawned by another node process, like:
var child = spawn('gulp', ['watch'], {
stdio: 'inherit',
});
And you try to kill it later, via:
child.kill();
This is how you handle the event [on the child]:
process.on('SIGTERM', function() {
console.log('Goodbye!');
});
Use --auto-open-devtools-for-tabs
flag while running chrome from command line
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --auto-open-devtools-for-tabs
https://developers.google.com/web/tools/chrome-devtools/open#auto
You might want to think about aspect-oriented programming. You don't want to litter your code with timings. You want to be able to turn them off and on declaratively.
If you use Spring, take a look at their MethodInterceptor class.
Since PHP 4 use error_reporting():
$site="http://www.google.com";
$old_error_reporting = error_reporting(E_ALL ^ E_WARNING);
$content = file_get_content($site);
error_reporting($old_error_reporting);
if ($content === FALSE) {
echo "Error getting '$site'";
} else {
echo $content;
}
The correct way to close the socket so you can re-open is:
tcpClient.Client.Disconnect(true);
The Boolean parameter indicates if you want to reuse the socket:
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
Try this from cmd line as Administrator
optional part, if you need to use a proxy:
set HTTP_PROXY=http://login:password@your-proxy-host:your-proxy-port
set HTTPS_PROXY=http://login:password@your-proxy-host:your-proxy-port
run this:
npm install -g --production windows-build-tools
No need for Visual Studio. This has what you need.
References:
https://www.npmjs.com/package/windows-build-tools
https://github.com/felixrieseberg/windows-build-tools
Note: The following only works for the next line of code, and only due to a coincidence.
With Lodash,
require('lodash');
_.isArray([]); // true
No var _ = require('lodash')
since Lodash mysteriously sets this value globally when required.
For modifying the status I think a RESTful approach is to use a logical sub-resource which describes the status of the resources. This IMO is pretty useful and clean when you have a reduced set of statuses. It makes your API more expressive without forcing the existing operations for your customer resource.
Example:
POST /customer/active <-- Providing entity in the body a new customer
{
... // attributes here except status
}
The POST service should return the newly created customer with the id:
{
id:123,
... // the other fields here
}
The GET for the created resource would use the resource location:
GET /customer/123/active
A GET /customer/123/inactive should return 404
For the PUT operation, without providing a Json entity it will just update the status
PUT /customer/123/inactive <-- Deactivating an existing customer
Providing an entity will allow you to update the contents of the customer and update the status at the same time.
PUT /customer/123/inactive
{
... // entity fields here except id and status
}
You are creating a conceptual sub-resource for your customer resource. It is also consistent with Roy Fielding's definition of a resource: "...A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time..." In this case the conceptual mapping is active-customer to customer with status=ACTIVE.
Read operation:
GET /customer/123/active
GET /customer/123/inactive
If you make those calls one right after the other one of them must return status 404, the successful output may not include the status as it is implicit. Of course you can still use GET /customer/123?status=ACTIVE|INACTIVE to query the customer resource directly.
The DELETE operation is interesting as the semantics can be confusing. But you have the option of not publishing that operation for this conceptual resource, or use it in accordance with your business logic.
DELETE /customer/123/active
That one can take your customer to a DELETED/DISABLED status or to the opposite status (ACTIVE/INACTIVE).
Answer to old question. But use ipython for this.
pip install ipython
ipython
import imaplib
imaplib?
This will give the following output about imaplib package -
Type: module
String form: <module 'imaplib' from '/usr/lib/python2.7/imaplib.py'>
File: /usr/lib/python2.7/imaplib.py
Docstring:
IMAP4 client.
Based on RFC 2060.
Public class: IMAP4
Public variable: Debug
Public functions: Internaldate2tuple
Int2AP
ParseFlags
Time2Internaldate
var result = listObject.Select( i => new{ i.category_name, i.category_id } )
This uses anonymous types so you must the var keyword, since the resulting type of the expression is not known in advance.
Use second process. Declare at AndroidManifest
new Service
with
android:process=":second"
Exchange between first and second process over BroadcastReceiver
The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.
>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200
You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding
class.
or try this
System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
System.Text.ASCIIEncoding.ASCII.GetByteCount(string);
By default, PHP permits uploading maximum 2 MB file on the server. But you can modify the maximum size of file upload as per your condition. By using the PHP configuration file php.ini, you can increase or decrease the file upload size in PHP.
First open the php.ini file in your text editor. Search the upload_max_filesize variable and stipulate the size which you want to increase.
Search for post_max_size variable and stipulate the size which you want to increase.
post_max_size = 128M
you can check this from here
I use File -> Switch Workspace -> Other... and type in my new workspace name.
(EDIT: Added the composite screen shot.)
Once in the new workspace, File -> Import... and under General choose "Existing Projects into Workspace. Press the Next button and then Browse for the old projects you would like to import. Check "Copy projects into workspace" to make a copy.
Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);
You can store the array using serialize
/unserialize
. With that solution they cannot easily be used from other programming languages, so you may consider using json_encode
/json_decode
instead (which gives you a widely supported format). Avoid using implode
/explode
for this since you'll probably end up with bugs or security flaws.
Note that this makes your table non-normalized, which may be a bad idea since you cannot easily query the data. Therefore consider this carefully before going forward. May you need to query the data for statistics or otherwise? Are there other reasons to normalize the data?
Also, don't save the raw $_POST
array. Someone can easily make their own web form and post data to your site, thereby sending a really large form which takes up lots of space. Save those fields you want and make sure to validate the data before saving it (so you won't get invalid values).
Built upon rsplak's answer. It uses jQuery's newer .on() instead of the deprecated .bind(). In addition to input, it will also work for select and other html elements. It will also disable the submit button if one of the fields becomes blank again.
var fields = "#user_input, #pass_input, #v_pass_input, #email";
$(fields).on('change', function() {
if (allFilled()) {
$('#register').removeAttr('disabled');
} else {
$('#register').attr('disabled', 'disabled');
}
});
function allFilled() {
var filled = true;
$(fields).each(function() {
if ($(this).val() == '') {
filled = false;
}
});
return filled;
}
Demo: JSFiddle
Google Instance ID
Released at I/O 2015; on Android requires play services 7.5.
https://developers.google.com/instance-id/
https://developers.google.com/instance-id/guides/android-implementation
InstanceID iid = InstanceID.getInstance( context ); // Google docs are wrong - this requires context
String id = iid.getId(); // blocking call
It seems that Google intends for this ID to be used to identify installations across Android, Chrome, and iOS.
It identifies an installation rather then a device, but then again, ANDROID_ID (which is the accepted answer) now no longer identifies devices either. With the ARC runtime a new ANDROID_ID is generated for every installation (details here), just like this new instance ID. Also, I think that identifying installations (not devices) is what most of us are actually looking for.
The advantages of instance ID
It appears to me that Google intends for it to be used for this purpose (identifying your installations), it is cross-platform, and can be used for a number of other purposes (see the links above).
If you use GCM, then you will eventually need to use this instance ID because you need it in order to get the GCM token (which replaces the old GCM registration ID).
The disadvantages/issues
In the current implementation (GPS 7.5) the instance ID is retrieved from a server when your app requests it. This means that the call above is a blocking call - in my unscientific testing it takes 1-3 seconds if the device is online, and 0.5 - 1.0 seconds if off-line (presumably this is how long it waits before giving up and generating a random ID). This was tested in North America on Nexus 5 with Android 5.1.1 and GPS 7.5.
If you use the ID for the purposes they intend - eg. app authentication, app identification, GCM - I think this 1-3 seconds could be a nuisance (depending on your app, of course).
You can use the Screen.PrimaryScreen.Bounds
to retrieve the size of the primary monitor (or inspect the Screen
object to retrieve all monitors). Use those with MyForms.Bounds
to figure out where to place your form.
First try to downgrade your angular version using "ng add @angular/material7.3..0" after that check if the error is gone in my case it is gone after that use this ng update @angular/material in case you are using angular 9 or 10 you have to write code like this import {MatInputModule} from 'angular/material/input' Hope it will work for you
I've found out that GPS does not need Internet, BUT of course if you need to download maps, you will need a data connection or wifi.
http://androidforums.com/samsung-fascinate/288871-gps-independent-3g-wi-fi.html http://www.droidforums.net/forum/droid-applications/63145-does-google-navigation-gps-requires-3g-work.html
I took the idea from @antron and implemented it differently: generating a true enum class.
This implementation meets all the requirements listed in original question but currently has only one real limitation: it assumes the enum values are either not provided or, if provided, must start with 0 and go up sequentially without gaps.
This is not an intrinsic limitation - simply that I don't use ad-hoc enum values. If this is needed, one can replace vector lookup with traditional switch/case implementation.
The solution uses some c++17 for inline variables but this can be easily avoided if needed. It also uses boost:trim because of simplicity.
Most importantly, it takes only 30 lines of code and no black magic macros. The code is below. It's meant to be put in header and included in multiple compilation modules.
It can be used the same way as was suggested earlier in this thread:
ENUM(Channel, int, Red, Green = 1, Blue)
std::out << "My name is " << Channel::Green;
//prints My name is Green
Pls let me know if this is useful and how it can be improved further.
#include <boost/algorithm/string.hpp>
struct EnumSupportBase {
static std::vector<std::string> split(const std::string s, char delim) {
std::stringstream ss(s);
std::string item;
std::vector<std::string> tokens;
while (std::getline(ss, item, delim)) {
auto pos = item.find_first_of ('=');
if (pos != std::string::npos)
item.erase (pos);
boost::trim (item);
tokens.push_back(item);
}
return tokens;
}
};
#define ENUM(EnumName, Underlying, ...) \
enum class EnumName : Underlying { __VA_ARGS__, _count }; \
struct EnumName ## Support : EnumSupportBase { \
static inline std::vector<std::string> _token_names = split(#__VA_ARGS__, ','); \
static constexpr const char* get_name(EnumName enum_value) { \
int index = (int)enum_value; \
if (index >= (int)EnumName::_count || index < 0) \
return "???"; \
else \
return _token_names[index].c_str(); \
} \
}; \
inline std::ostream& operator<<(std::ostream& os, const EnumName & es) { \
return os << EnumName##Support::get_name(es); \
}
If the migration has been run (read: migrated) then you should roll back your migration to clear the history from your database table. Once you're rolled back you should be able to safely delete your migration file and then proceed with migrating again.
You can also use one line to do that:
{{ yourVariable is not defined ? "Not Assigned" : "Assigned" }}
You cannot simply add a link using CSS. CSS is used for styling.
You can style your using CSS.
If you want to give a link dynamically to then I will advice you to use jQuery or Javascript.
You can accomplish that very easily using jQuery.
I have done a sample for you. You can refer that.
$('#link').attr('href','http://www.google.com');
This single line will do the trick.
It is possible to use patterns in a .gitignore
file. See the gitignore man page. The pattern */target/*
should ignore any directory named target and anything under it. Or you may try */target/**
to ignore everything under target.
found this and it worked for me.
strSQL = "SELECT * FROM DataTable"
'Where DataTable is the Named range
How can I run SQL statements on a named range within an excel sheet?
You may be overcomplicating things, is there any reason you need the stringr package?
df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
as.Date(df$Date, "%m/%d/%Y %H:%M:%S")
[1] "2009-10-09" "2009-10-15"
More generally and if you need the time component as well, use strptime:
strptime(df$Date, "%m/%d/%Y %H:%M:%S")
I'm guessing at what your actual data might look at from the partial results you give.
This happened to me when I was trying to push the develop branch (I am using git flow). Someone had push updates to master. to fix it I did:
git co master
git pull
Which fetched those changes. Then,
git co develop
git pull
Which didn't do anything. I think the develop branch already pushed despite the error message. Everything is up to date now and no errors.
Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.
One option is to replace table with CSS4 flex divs:
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
That works in new browsers i.e. IE11+ see table at the bottom of the article.
Encode or decode byte arrays:
byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded) // Outputs "Hello"
For more info, see Base64.
Base64 is not bundled with Java versions less than 8. I recommend using Apache Commons Codec.
For direct byte arrays:
Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = codec.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(codec.decodeBase64(encoded));
println(decoded) // Outputs "Hello"
If you're working in a Spring project already, you may find their org.springframework.util.Base64Utils
class more ergonomic:
For direct byte arrays:
byte[] encoded = Base64Utils.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte[] decoded = Base64Utils.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64Utils.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = Base64Utils.decodeFromString(encoded);
println(new String(decoded)) // Outputs "Hello"
If you are using the Android SDK before Java 8 then your best option is to use the bundled android.util.Base64
.
For direct byte arrays:
byte[] encoded = Base64.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte [] decoded = Base64.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.decode(encoded));
println(decoded) // Outputs "Hello"
I guess it might be because it is expecting a single value?
taken from the animate page on jQuery:
All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, width, height, or left can be animated but background-color cannot be.) Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.
Your python don't know where you installed scipy. add the scipy path to PYTHONPATH
and I hope it will solve your problem.
I prefer the second way.
When you use the first way, if you decide to use a parallel stream to improve performance, you'll have no control over the order in which the elements will be added to the output list by forEach
.
When you use toList
, the Streams API will preserve the order even if you use a parallel stream.
You could add the user to the Database Level Role db_datareader.
Members of the db_datareader fixed database role can run a SELECT statement against any table or view in the database.
See Books Online for reference:
http://msdn.microsoft.com/en-us/library/ms189121%28SQL.90%29.aspx
You can add a database user to a database role using the following query:
EXEC sp_addrolemember N'db_datareader', N'userName'
In options object you have used "=" sign to assign value to port but we have to use ":" to assign values to properties in object when using object literal to create an object i.e."{}" ,these curly brackets. Even when you use function expression or create an object inside object you have to use ":" sign. for e.g.:
var rishabh = {
class:"final year",
roll:123,
percent: function(marks1, marks2, marks3){
total = marks1 + marks2 + marks3;
this.percentage = total/3 }
};
john.percent(85,89,95);
console.log(rishabh.percentage);
here we have to use commas "," after each property. but you can use another style to create and initialize an object.
var john = new Object():
john.father = "raja"; //1st way to assign using dot operator
john["mother"] = "rani";// 2nd way to assign using brackets and key must be string
I will try to get the answer with one query using CTE and window function rank()
create the tables
create table Students
(student_id int,
Name varchar(255),
details varchar(255));
create table Subject(
Sub_id int,
name varchar(255));
create table marks
(student_id int,
subject_id int,
mark int);
the answer should be a table with the below fields
student_name | subject_name | mark
plan the execution steps
with CTE as (select s.name, sb.name as subject_name, m.mark, rank() over(partition by sb.name order by m.mark desc) as rn
from Students s
join marks m on s.student_id = m.student_id
join subject sb
on sb.Sub_id = m.subject_id)
select name , subject_name, mark
from CTE
where rn = 1
I've faced the same problem because of a cable. I changed my third party USB/lighting cable into original Apple cable, and it worked.
You cannot use ++
on something which is not a variable, this would be the closest you can get:
$('#counter').html(function(i, val) { return +val+1 });
jQuery's html()
method can get and set the HTML value of an element. If passed a function it can update the HTML based upon the existing value. So in the context of your code:
$("#update").click(function() {
$('#counter').html(function(i, val) { return +val+1 });
}
DEMO: http://jsfiddle.net/marcuswhybrow/zRX2D/2/
When it comes to synchronising your counter on the page, with the counter value in your database, never trust the client! You send either an increment or decrement signal to you server side script, rather than a continuous value such as 10, or 23.
However you could send an AJAX request to the server when you change the HTML of your counter:
$("#update").click(function() {
$('#counter').html(function(i, val) {
$.ajax({
url: '/path/to/script/',
type: 'POST',
data: {increment: true},
success: function() { alert('Request has returned') }
});
return +val+1;
});
}
The solution found here helped us to update master to a previous commit that had already been pushed:
git checkout master
git reset --hard e3f1e37
git push --force origin e3f1e37:master
The key difference from the accepted answer is the commit hash "e3f1e37:" before master in the push command.
Simply select the project and press CTRL + B.
If your InputStream is backed by a Socket, you can set a Socket timeout (in milliseconds) using setSoTimeout. If the read() call doesn't unblock within the timeout specified, it will throw a SocketTimeoutException.
Just make sure that you call setSoTimeout on the Socket before making the read() call.
import java.math.*;
public class TestRound11 {
public static void main(String args[]){
double d = 3.1537;
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
// output is 3.15
System.out.println(d + " : " + round(d, 2));
// output is 3.154
System.out.println(d + " : " + round(d, 3));
}
public static double round(double d, int decimalPlace){
// see the Javadoc about why we use a String in the constructor
// http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(double)
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
}
I had the same problem, and it was related to XSS (cross site scripting) block by the browser. I managed to make it work using a server.
Take a look at: http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/282972/why-am-i-getting-xmlhttprequest.status0
After opening the file, list comprehension can do this in one line:
fh=open('filename')
newlist = [line.rstrip() for line in fh.readlines()]
fh.close()
Just remember to close your file afterwards.
In workbench 6.0 Connect to any of the database. You will see two tabs.
1.Management
2. Schemas
By default Schemas
tab is selected.
Select Management
tab
then select Data Export
.
You will get list of all databases.
select the desired database and and the file name and ther options you wish and start export.
You are done with backup.
Besides the most common approach with Period and Duration objects you can widen your knowledge with another way for dealing with time in Java.
Advanced Java 8 libraries. ChronoUnit for Differences.
ChronoUnit is a great way to determine how far apart two Temporal values are. Temporal includes LocalDate, LocalTime and so on.
LocalTime one = LocalTime.of(5,15);
LocalTime two = LocalTime.of(6,30);
LocalDate date = LocalDate.of(2019, 1, 29);
System.out.println(ChronoUnit.HOURS.between(one, two)); //1
System.out.println(ChronoUnit.MINUTES.between(one, two)); //75
System.out.println(ChronoUnit.MINUTES.between(one, date)); //DateTimeException
First example shows that between truncates rather than rounds.
The second shows how easy it is to count different units.
And the last example reminds us that we should not mess up with dates and times in Java :)
You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.
http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
Here is the Koltin style, I use this in my project and it works very well:
this.yourview.setOnTouchListener(View.OnTouchListener { _, event ->
val x = event.x
val y = event.y
when(event.action) {
MotionEvent.ACTION_DOWN -> {
Log.d(TAG, "ACTION_DOWN \nx: $x\ny: $y")
}
MotionEvent.ACTION_MOVE -> {
Log.d(TAG, "ACTION_MOVE \nx: $x\ny: $y")
}
MotionEvent.ACTION_UP -> {
Log.d(TAG, "ACTION_UP \nx: $x\ny: $y")
}
}
return@OnTouchListener true
})
Try doing it the other way around.
$('<link rel="stylesheet" href="css/style2.css" type="text/css" />').appendTo('head');
A little late to the party, but since I was looking for it (and I might need to find it again sometime), here's what I did to include version, company name, etc. into my C++ DLL under VS2013 Express:
Hope this helps!
You can use the autocorrect lib to spell check in python.
Example Usage:
from autocorrect import Speller
spell = Speller(lang='en')
print(spell('caaaar'))
print(spell('mussage'))
print(spell('survice'))
print(spell('hte'))
Result:
caesar
message
service
the
Use the btoa()
function to encode:
console.log(btoa("password")); // cGFzc3dvcmQ=
_x000D_
To decode, you can use the atob()
function:
console.log(atob("cGFzc3dvcmQ=")); // password
_x000D_
https://github.com/cognitom/paper-css seems to solve all my needs.
Front-end printing solution - previewable and live-reloadable!
For all the Kotlin developers out there:
Here is the Android Studio proposed solution to send data to your Fragment (= when you create a Blank-Fragment with File -> New -> Fragment -> Fragment(Blank) and you check "include fragment factory methods").
Put this in your Fragment:
class MyFragment: Fragment {
...
companion object {
@JvmStatic
fun newInstance(isMyBoolean: Boolean) = MyFragment().apply {
arguments = Bundle().apply {
putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean)
}
}
}
}
.apply
is a nice trick to set data when an object is created, or as they state here:
Calls the specified function [block] with
this
value as its receiver and returnsthis
value.
Then in your Activity or Fragment do:
val fragment = MyFragment.newInstance(false)
... // transaction stuff happening here
and read the Arguments in your Fragment such as:
private var isMyBoolean = false
override fun onAttach(context: Context?) {
super.onAttach(context)
arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let {
isMyBoolean = it
}
}
To "send" data back to your Activity, simply define a function in your Activity and do the following in your Fragment:
(activity as? YourActivityClass)?.callYourFunctionLikeThis(date) // your function will not be called if your Activity is null or is a different Class
Enjoy the magic of Kotlin!
Just spent a hour or so doing this and with the help of Brad's advice and a few additional changes it all worked.
I've done this using the following: 10.7.3, Xcode 4.3.2, iOS 5.1 btw.
1) Right click on your myapp.xcodeproj
and select package contents
2) open project.pbxproj
with a text editor (don't recommend textedit as it may screw up the formatting)
3) Scroll all the way down until you find /* Begin XCBuildConfiguration section */
4) Notice that you have a debug and release sections
5) In the release section take a look at CODE_SIGN_IDENTITY
& "CODE_SIGN_IDENTITY[sdk=iphoneos*]"
it should look something like this:
CODE_SIGN_IDENTITY = "iPhone Distribution: MyCompany LLC";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution: MyCompany LLC";
6) Take a look at PROVISIONING_PROFILE
and "PROVISIONING_PROFILE[sdk=iphoneos*]"
they should look like this:
PROVISIONING_PROFILE = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
"PROVISIONING_PROFILE[sdk=iphoneos*]" = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
This should match your provisioning profile in Xcode. To see if they match open Xcode > Window > Organizer > Devices > Provisioning Profiles > Right click on the profile > Reveal in Finder > The filename of the .mobileprovision is your profile id.
7) Scroll down in the project.pbxproj
and find a second instance of the release section. The second instance of the release section should end with a comment saying /* End XCBuildConfiguration section */
8) make sure that the second section matches the first section so that CODE_SIGN_IDENTITY, "CODE_SIGN_IDENTITY[sdk=iphoneos*]
, and PROVISIONING_PROFILE
are all filled in.
You can use isLetter(char c) static method of Character class in Java.lang .
public boolean isAlpha(String s) {
char[] charArr = s.toCharArray();
for(char c : charArr) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
To add to the other answers, by implementating java.io.Serializable
, you get "automatic" serialization capability for objects of your class. No need to implement any other logic, it'll just work. The Java runtime will use reflection to figure out how to marshal and unmarshal your objects.
In earlier version of Java, reflection was very slow, and so serializaing large object graphs (e.g. in client-server RMI applications) was a bit of a performance problem. To handle this situation, the java.io.Externalizable
interface was provided, which is like java.io.Serializable
but with custom-written mechanisms to perform the marshalling and unmarshalling functions (you need to implement readExternal
and writeExternal
methods on your class). This gives you the means to get around the reflection performance bottleneck.
In recent versions of Java (1.3 onwards, certainly) the performance of reflection is vastly better than it used to be, and so this is much less of a problem. I suspect you'd be hard-pressed to get a meaningful benefit from Externalizable
with a modern JVM.
Also, the built-in Java serialization mechanism isn't the only one, you can get third-party replacements, such as JBoss Serialization, which is considerably quicker, and is a drop-in replacement for the default.
A big downside of Externalizable
is that you have to maintain this logic yourself - if you add, remove or change a field in your class, you have to change your writeExternal
/readExternal
methods to account for it.
In summary, Externalizable
is a relic of the Java 1.1 days. There's really no need for it any more.
You can add to the system-path at runtime:
import sys
sys.path.insert(0, 'path/to/your/py_file')
import py_file
This is by far the easiest way to do it.
The easiest and fastest way would be with phpmyadmin structure table.
There it's in Russian language but in English Version should be the same. Just click Unique button. Also from there you can make your columns PRIMARY or DELETE.
I'd rather use static widths and if you'd like your page to resize depending on screen size, you can have a look at media queries.
Or, you can set a min-width on elements like header, navigation, content etc.
PuTTY Session Manager is a tool that allows system administrators to organise their PuTTY sessions into folders and assign hotkeys to favourite sessions. Multiple sessions can be launched with one click. Requires MS Windows and the .NET 2.0 Runtime.
Just a supplement here.
The following question is that what if I want more subplots in the figure?
As mentioned in the Doc, we can use fig = plt.subplots(nrows=2, ncols=2)
to set a group of subplots with grid(2,2) in one figure object.
Then as we know, the fig, ax = plt.subplots()
returns a tuple, let's try fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2)
firstly.
ValueError: not enough values to unpack (expected 4, got 2)
It raises a error, but no worry, because we now see that plt.subplots()
actually returns a tuple with two elements. The 1st one must be a figure object, and the other one should be a group of subplots objects.
So let's try this again:
fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)
and check the type:
type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>
Of course, if you use parameters as (nrows=1, ncols=4), then the format should be:
fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)
So just remember to keep the construction of the list as the same as the subplots grid we set in the figure.
Hope this would be helpful for you.
As @fijaaron says,
GRANT ALL
does not imply GRANT FILE
GRANT FILE
only works with *.*
So do
GRANT FILE ON *.* TO user;
If you have luasocket installed:
local socket = require 'socket'
socket.sleep(0.2)
If you are a Jenkins administrator you can use the Jenkins system information page:
http://<jenkinsurl>/systemInfo
There are only two ways:
If the memory pointer to by your char *
represents a C string (that is, it contains characters that have a 0-byte to mark its end), you can use strlen(a)
.
Otherwise, you need to store the length somewhere. Actually, the pointer only points to one char
. But we can treat it as if it points to the first element of an array. Since the "length" of that array isn't known you need to store that information somewhere.
Consider the hex() method of the bytes
type on Python 3.5 and up:
>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print(bytes(array_alpha).hex())
8535eaf1
EDIT: it's also much faster than hexlify
(modified @falsetru's benchmarks above)
from timeit import timeit
N = 10000
print("bytearray + hexlify ->", timeit(
'binascii.hexlify(data).decode("ascii")',
setup='import binascii; data = bytearray(range(255))',
number=N,
))
print("byte + hex ->", timeit(
'data.hex()',
setup='data = bytes(range(255))',
number=N,
))
Result:
bytearray + hexlify -> 0.011218150997592602
byte + hex -> 0.005952142993919551
Quoting directly from the help page for factor
:
To transform a factor f to its original numeric values, as.numeric(levels(f))[f]
is recommended and slightly more efficient than as.numeric(as.character(f))
.
I guess an img tag is needed as a child of an a tag, the following way:
<a download="YourFileName.jpeg" href="data:image/jpeg;base64,iVBO...CYII=">
<img src="data:image/jpeg;base64,iVBO...CYII="></img>
</a>
or
<a download="YourFileName.jpeg" href="/path/to/OtherFile.jpg">
<img src="/path/to/OtherFile.jpg"></img>
</a>
Only using the a tag as explained in #15 didn't worked for me with the latest version of Firefox and Chrome, but putting the same image data in both a.href and img.src tags worked for me.
From JavaScript it could be generated like this:
var data = canvas.toDataURL("image/jpeg");
var img = document.createElement('img');
img.src = data;
var a = document.createElement('a');
a.setAttribute("download", "YourFileName.jpeg");
a.setAttribute("href", data);
a.appendChild(img);
var w = open();
w.document.title = 'Export Image';
w.document.body.innerHTML = 'Left-click on the image to save it.';
w.document.body.appendChild(a);
Use the Below Code for that
UPDATE Table1 SET Column1 = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(Column1, CHAR(9), ''), CHAR(10), ''), CHAR(13), '')))`
best way is
button.setBackgroundResource(android.R.drawable.ic_delete);
OR this for Drawable left and something like that for right etc.
int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);
and
getResources().getDrawable()
is now deprecated
It is surprisingly simple...
Code behind:
// Here's your object that you'll create a list of
private class Products
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductPrice { get; set; }
}
// Here you pass in the List of Products
private void BindItemsInCart(List<Products> ListOfSelectedProducts)
{
// The the LIST as the DataSource
this.rptItemsInCart.DataSource = ListOfSelectedProducts;
// Then bind the repeater
// The public properties become the columns of your repeater
this.rptItemsInCart.DataBind();
}
ASPX code:
<asp:Repeater ID="rptItemsInCart" runat="server">
<HeaderTemplate>
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Product Description</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("ProductName") %></td>
<td><%# Eval("ProductDescription")%></td>
<td><%# Eval("ProductPrice")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
I hope this helps!
04/2020: Corrected old answer
Use :selected pseudo selector on the selected options and then use the .val function to get the value of the option.
$('select[name=selector] option').filter(':selected').val()
Side note: Using filter is better then using :selected
selector directly in the first query.
If inside a change handler, you could use simply this.value
to get the selected option value. See demo for more options.
//ways to retrieve selected option and text outside handler
console.log('Selected option value ' + $('select option').filter(':selected').val());
console.log('Selected option value ' + $('select option').filter(':selected').text());
$('select').on('change', function () {
//ways to retrieve selected option and text outside handler
console.log('Changed option value ' + this.value);
console.log('Changed option text ' + $(this).find('option').filter(':selected').text());
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<select>
<option value="1" selected>1 - Text</option>
<option value="2">2 - Text</option>
<option value="3">3 - Text</option>
<option value="4">4 - Text</option>
</select>
_x000D_
Old answer:
Edit: As many pointed out, this does not returns the selected option value.
~~Use .val to get the value of the selected option. See below,
$('select[name=selector]').val()~~
Easiest and sample way.
bool bol=Array.Exists(stringarray,E => E == stringtocheck);
This can happen when you change the data annotation of a model property. for example: adding [Required] to a property will cause a pending change in the database design.
The safest solution is to run on the Package Manager Console:
add-migration myMirgrationName
which will display the exact changes in the Up() method. Therefore, you can decide if you really want to apply such changes via the:
update-database
Otherwise, you may just delete the latest migration from the __MigrationHistory table and from the Migrations folder the Solution Explorer.
Using brew
First install brew:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
And then install wget with brew:
brew install wget
Using MacPorts
First, download and run MacPorts installer (.pkg)
And then install wget:
sudo port install wget
Truncating the table wont be possible even if you disable the foreign keys.so you can use delete command to remove all the records from the table,but be aware if you are using delete command for a table which consists of millions of records then your package will be slow and your transaction log size will increase and it may fill up your valuable disk space.
If you drop the constraints it may happen that you will fill up your table with unclean data and when you try to recreate the constraints it may not allow you to as it will give errors. so make sure that if you drop the constraints,you are loading data which are correctly related to each other and satisfy the constraint relations which you are going to recreate.
so please carefully think the pros and cons of each method and use it according to your requirements
Do this.
var x=parseInt(document.forms["frmOrder"]["txtTotal"].value);
var y=parseInt(document.forms["frmOrder"]["totalpoints"].value);
Andrew's answer is good.
And just to help you out a bit more, here's how you use multiple formatting in one string
"Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike".
If you are using ints instead of string, use %d instead of %s.
"My name is %s and i'm %d" % ('john', 12) #My name is john and i'm 12
I have a sample app where I prepare the intent and just pass the CITY_NAME in the intent to the maps marker activity which eventually calculates longitude and latitude by Geocoder using CITY_NAME.
Below is the code snippet of starting the maps marker activity and the complete MapsMarkerActivity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} else if (id == R.id.action_refresh) {
Log.d(APP_TAG, "onOptionsItemSelected Refresh selected");
new MainActivityFragment.FetchWeatherTask().execute(CITY, FORECAS_DAYS);
return true;
} else if (id == R.id.action_map) {
Log.d(APP_TAG, "onOptionsItemSelected Map selected");
Intent intent = new Intent(this, MapsMarkerActivity.class);
intent.putExtra("CITY_NAME", CITY);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public class MapsMarkerActivity extends AppCompatActivity
implements OnMapReadyCallback {
private String cityName = "";
private double longitude;
private double latitude;
static final int numberOptions = 10;
String [] optionArray = new String[numberOptions];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_map);
// Get the SupportMapFragment and request notification
// when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Test whether geocoder is present on platform
if(Geocoder.isPresent()){
cityName = getIntent().getStringExtra("CITY_NAME");
geocodeLocation(cityName);
} else {
String noGoGeo = "FAILURE: No Geocoder on this platform.";
Toast.makeText(this, noGoGeo, Toast.LENGTH_LONG).show();
return;
}
}
/**
* Manipulates the map when it's available.
* The API invokes this callback when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user receives a prompt to install
* Play services inside the SupportMapFragment. The API invokes this method after the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(latitude, longitude);
// If cityName is not available then use
// Default Location.
String markerDisplay = "Default Location";
if (cityName != null
&& cityName.length() > 0) {
markerDisplay = "Marker in " + cityName;
}
googleMap.addMarker(new MarkerOptions().position(sydney)
.title(markerDisplay));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
/**
* Method to geocode location passed as string (e.g., "Pentagon"), which
* places the corresponding latitude and longitude in the variables lat and lon.
*
* @param placeName
*/
private void geocodeLocation(String placeName){
// Following adapted from Conder and Darcey, pp.321 ff.
Geocoder gcoder = new Geocoder(this);
// Note that the Geocoder uses synchronous network access, so in a serious application
// it would be best to put it on a background thread to prevent blocking the main UI if network
// access is slow. Here we are just giving an example of how to use it so, for simplicity, we
// don't put it on a separate thread. See the class RouteMapper in this package for an example
// of making a network access on a background thread. Geocoding is implemented by a backend
// that is not part of the core Android framework, so we use the static method
// Geocoder.isPresent() to test for presence of the required backend on the given platform.
try{
List<Address> results = null;
if(Geocoder.isPresent()){
results = gcoder.getFromLocationName(placeName, numberOptions);
} else {
Log.i(MainActivity.APP_TAG, "No Geocoder found");
return;
}
Iterator<Address> locations = results.iterator();
String raw = "\nRaw String:\n";
String country;
int opCount = 0;
while(locations.hasNext()){
Address location = locations.next();
if(opCount == 0 && location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
country = location.getCountryName();
if(country == null) {
country = "";
} else {
country = ", " + country;
}
raw += location+"\n";
optionArray[opCount] = location.getAddressLine(0)+", "
+location.getAddressLine(1)+country+"\n";
opCount ++;
}
// Log the returned data
Log.d(MainActivity.APP_TAG, raw);
Log.d(MainActivity.APP_TAG, "\nOptions:\n");
for(int i=0; i<opCount; i++){
Log.i(MainActivity.APP_TAG, "("+(i+1)+") "+optionArray[i]);
}
Log.d(MainActivity.APP_TAG, "latitude=" + latitude + ";longitude=" + longitude);
} catch (Exception e){
Log.d(MainActivity.APP_TAG, "I/O Failure; do you have a network connection?",e);
}
}
}
Links expire so i have pasted complete code above but just in case if you would like to see complete code then its available at : https://github.com/gosaliajigar/CSC519/tree/master/CSC519_HW4_89753
I think create a custom EditorTemplate is not good solution, beause you need to care about many possible tepmlates for different cases: strings, numsers, comboboxes and so on. Other solution is custom extention to HtmlHelper.
Model:
public class MyViewModel
{
[PlaceHolder("Enter title here")]
public string Title { get; set; }
}
Html helper extension:
public static MvcHtmlString BsEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TValue>> expression, string htmlClass = "")
{
var modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var metadata = modelMetadata;
var viewData = new
{
HtmlAttributes = new
{
@class = htmlClass,
placeholder = metadata.Watermark,
}
};
return htmlHelper.EditorFor(expression, viewData);
}
A corresponding view:
@Html.BsEditorFor(x => x.Title)
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);
//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns)
Try cast (columnName as unsigned)
unsigned is positive value only
If you want to include negative value, then cast (columnName as signed)
,
The difference between sign (negative include) and unsigned (twice the size of sign, but non-negative)
Just check if response[0]
is undefined:
if(response[0] !== undefined) { ... }
If you still need to explicitly check the title, do so after the initial check:
if(response[0] !== undefined && response[0].title !== undefined){ ... }
You are right the urllib and urllib2 packages have been split into urllib.request , urllib.parse and urllib.error packages in Python 3.x. The latter packages do not exist in Python 2.x
From documentation -
The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error.
From urllib2 documentation -
The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error.
So I am pretty sure the code you downloaded has been written for Python 3.x , since they are using a library that is only present in Python 3.x .
There is a urllib package in python, but it does not have the request subpackage. Also, lets assume you do lots of work and somehow make request subpackage available in Python 2.x .
There is a very very high probability that you will run into more issues, there is lots of incompatibility between Python 2.x and Python 3.x , in the end you would most probably end up rewriting atleast half the code from github (and most probably reading and understanding the complete code from there).
Even then there may be other bugs arising from the fact that some of the implementation details changed between Python 2.x to Python 3.x (As an example - list comprehension got its own namespace in Python 3.x)
You are better off trying to download and use Python 3 , than trying to make code written for Python 3.x compatible with Python 2.x
Set the value it will set it as selected option for dropdown:
$("#salesrep").val("Bruce Jones");
If it still not working:
Example of how to perform a INSERT INTO SELECT with a WHERE clause.
INSERT INTO #test2 (id) SELECT id FROM #test1 WHERE id > 2
I have developed pure XML based word files in the past. I used .NET, but the language should not matter since it's truely XML. It was not the easiest thing to do (had a project that required it a couple years ago.) These do only work in Word 2007 or above - but all you need is Microsoft's white paper that describe what each tag does. You can accomplish all you want with the tags the same way as if you were using Word (of course a little more painful initially.)
You're apparently off by one day, exactly 86400 seconds. Use the number 2209161600 Not the number 2209075200 If you Google the two numbers, you'll find support for the above. I tried your formula but was always coming up 1 day different from my server. It's not obvious from the unix timestamp unless you think in unix instead of human time ;-) but if you double check then you'll see this might be correct.
In my case I was using it on localhost
and forgot to change RewriteBase
in .htaccess
.
I had the same problem. I wanted to create a view to show information of the most recent year, from a table with records from 2009 to 2011. Here's the original query:
SELECT a.*
FROM a
JOIN (
SELECT a.alias, MAX(a.year) as max_year
FROM a
GROUP BY a.alias
) b
ON a.alias=b.alias and a.year=b.max_year
Outline of solution:
Here's the solution query:
CREATE VIEW v_max_year AS
SELECT alias, MAX(year) as max_year
FROM a
GROUP BY a.alias;
CREATE VIEW v_latest_info AS
SELECT a.*
FROM a
JOIN v_max_year b
ON a.alias=b.alias and a.year=b.max_year;
It works fine on mysql 5.0.45, without much of a speed penalty (compared to executing the original sub-query select without any views).
You can use:
var dictionary = myList.ToDictionary(x => x);
To expound upon @clyfe's answer. You can get a list of your instance methods using the following code (assuming that you have an Object Class named "Parser"):
Parser.new.methods - Object.new.methods
Like ?egDwight said, you can use the HTML entity &infin
; or ∞
. A easy source of getting these codes, is to look at this entity list.
You can also use them in CSS, which was what I was looking for, just like font-awesome does. A simple CSS based solution would be to have something like:
.infinity-ico:before {
content: '\221E';
}
As much as your available memory will allow. There's no size limit except for the heap.
You can also add padding for a nice effect.
<img src="image.png" style="padding:1px;border:thin solid black;">
This is my code,tested and working fine:
package com.example.com.mak.mediaplayer;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mpp = MediaPlayer.create(this, R.raw.red); //mp3 file in res/raw folder
Button btnplay = (Button) findViewById(R.id.btnplay); //Play
btnplay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vone) {
mpp.start();
}
});
Button btnpause = (Button) findViewById(R.id.btnpause); //Pause
btnpause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vtwo) {
if (mpp.isPlaying()) {
mpp.pause();
mpp.seekTo(0);
}
}
});
}
}
Try xcorr
, it's a built-in function in MATLAB for cross-correlation:
c = xcorr(A_1, A_2);
However, note that it requires the Signal Processing Toolbox installed. If not, you can look into the corrcoef
command instead.
I had DependencyResolutionException
in Ubuntu Linux when I've installed local artifacts via a shell script. The solution was to delete the local artifacts and install them again "manually" - calling mvn install:install-file
via terminal.
You can specify a environment variable named PORT
to specify the port on which the server will run.
$ export PORT=3005 #Linux
$ $env:PORT=3005 # Windows - Powershell
Remove the project from your solution by right-clicking it in the Solution Explorer window and choosing Remove. Move the entire project folder, including subdirectories wherever you want it to go. Add the project back to your solution.
Namespace names is something completely different, just edit the source code.
You might be looking for Promise.race
(native I/O racing solution, not threads)
Assuming you (or others searching this question) want to race threads to avoid failure and avoid the cost of I/O operations, this is a simple and native way to accomplish it (which does not use threads). Node is designed to be single threaded (look up the event loop), so avoid using threads if possible. If my assumption is correct, I recommend you use Promise.race
with setTimeout
(example in link). With this strategy, you would race a list of promises which each try some I/O operation and reject the promise if there is an error (otherwise timeout). The Promise.race
statement continues after the first resolution/rejection, which seems to be what you want. Hope this helps someone!
This is a method you can do using the basic JavaScript, which is works for me:
var v_Result;
function OneClick() {
v_Result = false;
window.setTimeout(OneClick_Nei, 500)
function OneClick_Nei() {
if (v_Result != false) return;
alert("single click");
}
}
function TwoClick() {
v_Result = true;
alert("double click");
}
Can be solved using a simple directive "go-back-history", this one is also closing window in case of no previous history.
Directive usage
<a data-go-back-history>Previous State</a>
Angular directive declaration
.directive('goBackHistory', ['$window', function ($window) {
return {
restrict: 'A',
link: function (scope, elm, attrs) {
elm.on('click', function ($event) {
$event.stopPropagation();
if ($window.history.length) {
$window.history.back();
} else {
$window.close();
}
});
}
};
}])
Note: Working using ui-router or not.
location ~ /issue([0-9]+) {
return 301 http://example.com/shop/issues/custom_isse_name$1;
}
You can use javascript to access elements on the page and modify their contents. So for example you might have a page with some HTML markup like so:
<div id="MyEdit">
This text will change
</div>
You can use javascript to change the content like so...
document.getElementById("MyEdit").innerHTML = "My new text!";?
You can also look at using the JQuery javascript library for DOM manipulation, it has some great features to make things like this very easy.
For example, with JQuery, you could do this to acheive the same result...
$("#MyEdit").html("My new text!");
Here is a working example of the JQuery version
Based on this example you provided in your post. The following JQuery would work for you:
var x = "hello wolrd";
$("p").html(x);
Using a P
tag like this however is not recommended. You would ideally want to use an element with a unique ID so you can ensure you are selecting the correct one with JQuery.
Not yet mentioned here, another choice is environment aligned
, again from package amsmath
:
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{equation}
\begin{aligned}
A & = B + C\\
& = D + E + F\\
& = G
\end{aligned}
\end{equation}
\end{document}
This outputs:
If you're running Windows 8/Windows Server 2012 or newer, you can use the Test-NetConnection command in PowerShell.
Ex:
Test-NetConnection -Port 53 -ComputerName LON-DC1
I've written a small shell script, tapt, for Debian based system. esp. Ubuntu. What it basically does is to post all your "apt-get" activities to your twitter account. It helps me to keep the track of what and when I've installed/remove programs in my Ubuntu system. I created a new Twitter account just for this and kept it private. Really useful. More information here: http://www.quicktweaks.com/tapt/
The problem is the indexing subplot
is using. Subplots are counted starting with 1!
Your code thus needs to read
fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):
#this part is just arranging the data for contourf
ind2 = py.find(zz==i+1)
sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
sfr_mass_sub = sfr_mass[ind2]
zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')
temp = 251+i # this is to index the position of the subplot
ax=plt.subplot(temp)
ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
plt.subplots_adjust(hspace = .5,wspace=.001)
#just annotating where each contour plot is being placed
ax.set_title(str(temp))
Note the change in the line where you calculate temp
Try to declare UseHttpGet over your method.
[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
return "Hello World";
}
I will explain you this with a practical example and no theory stuff:
A developer writes the code. No GUI is implemented yet. The testing at this level verifies that the functions work correctly and the data types are correct. This phase of testing is called Unit testing.
When a GUI is developed, and application is assigned to a tester, he verifies business requirements with a client and executes the different scenarios. This is called functional testing. Here we are mapping the client requirements with application flows.
Integration testing: let's say our application has two modules: HR and Finance. HR module was delivered and tested previously. Now Finance is developed and is available to test. The interdependent features are also available now, so in this phase, you will test communication points between the two and will verify they are working as requested in requirements.
Regression testing is another important phase, which is done after any new development or bug fixes. Its aim is to verify previously working functions.
From what I can see there are helper methods inside the ControllerBase
class. Just use the StatusCode
method:
[HttpPost]
public IActionResult Post([FromBody] string something)
{
//...
try
{
DoSomething();
}
catch(Exception e)
{
LogException(e);
return StatusCode(500);
}
}
You may also use the StatusCode(int statusCode, object value)
overload which also negotiates the content.
You need to create a new XAttribute
instead of XElement
. Try something like this:
public static void Test()
{
var xdoc = XDocument.Parse(@"
<Snippets>
<Snippet name='abc'>
<SnippetCode>
testcode1
</SnippetCode>
</Snippet>
<Snippet name='xyz'>
<SnippetCode>
testcode2
</SnippetCode>
</Snippet>
</Snippets>");
xdoc.Root.Add(
new XElement("Snippet",
new XAttribute("name", "name goes here"),
new XElement("SnippetCode", "SnippetCode"))
);
xdoc.Save(@"C:\TEMP\FOO.XML");
}
This generates the output:
<?xml version="1.0" encoding="utf-8"?>
<Snippets>
<Snippet name="abc">
<SnippetCode>
testcode1
</SnippetCode>
</Snippet>
<Snippet name="xyz">
<SnippetCode>
testcode2
</SnippetCode>
</Snippet>
<Snippet name="name goes here">
<SnippetCode>SnippetCode</SnippetCode>
</Snippet>
</Snippets>
but as for this method, I don't understand the purpose of Integer.MAX_VALUE and Integer.MIN_VALUE.
By starting out with smallest
set to Integer.MAX_VALUE
and largest
set to Integer.MIN_VALUE
, they don't have to worry later about the special case where smallest
and largest
don't have a value yet. If the data I'm looking through has a 10
as the first value, then numbers[i]<smallest
will be true (because 10
is <
Integer.MAX_VALUE
) and we'll update smallest
to be 10
. Similarly, numbers[i]>largest
will be true
because 10
is >
Integer.MIN_VALUE
and we'll update largest
. And so on.
Of course, when doing this, you must ensure that you have at least one value in the data you're looking at. Otherwise, you end up with apocryphal numbers in smallest
and largest
.
Note the point Onome Sotu makes in the comments:
...if the first item in the array is larger than the rest, then the largest item will always be Integer.MIN_VALUE because of the else-if statement.
Which is true; here's a simpler example demonstrating the problem (live copy):
public class Example
{
public static void main(String[] args) throws Exception {
int[] values = {5, 1, 2};
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
for (int value : values) {
if (value < smallest) {
smallest = value;
} else if (value > largest) {
largest = value;
}
}
System.out.println(smallest + ", " + largest); // 1, 2 -- WRONG
}
}
To fix it, either:
Don't use else
, or
Start with smallest
and largest
equal to the first element, and then loop the remaining elements, keeping the else if
.
Here's an example of that second one (live copy):
public class Example
{
public static void main(String[] args) throws Exception {
int[] values = {5, 1, 2};
int smallest = values[0];
int largest = values[0];
for (int n = 1; n < values.length; ++n) {
int value = values[n];
if (value < smallest) {
smallest = value;
} else if (value > largest) {
largest = value;
}
}
System.out.println(smallest + ", " + largest); // 1, 5
}
}
Arrays can hold pointers so when I want an array of objects I do that.
$a = array();
$o = new Whatever_Class();
$a[] = &$o;
print_r($a);
This will show that the object is referenced and accessible through the array.
If you're doing the check inside the View, put the value in the ViewBag
.
In your controller:
ViewBag["parameterName"] = Request["parameterName"];
It's worth noting that the Request
and Response
properties are exposed by the Controller
class. They have the same semantics as HttpRequest
and HttpResponse
.
People run into this error when the Node.js process is still running and they are attempting to start the server again. Try this:
ps aux | grep node
This will print something along the lines of:
user 7668 4.3 1.0 42060 10708 pts/1 Sl+ 20:36 0:00 node server
user 7749 0.0 0.0 4384 832 pts/8 S+ 20:37 0:00 grep --color=auto node
In this case, the process will be the one with the pid 7668. To kill it and restart the server, run kill -9 7668
.
i improved the function a head to be this :
var minifyImg = function(dataUrl,newWidth,imageType="image/jpeg",resolve,imageArguments=0.7){
var image, oldWidth, oldHeight, newHeight, canvas, ctx, newDataUrl;
(new Promise(function(resolve){
image = new Image(); image.src = dataUrl;
log(image);
resolve('Done : ');
})).then((d)=>{
oldWidth = image.width; oldHeight = image.height;
log([oldWidth,oldHeight]);
newHeight = Math.floor(oldHeight / oldWidth * newWidth);
log(d+' '+newHeight);
canvas = document.createElement("canvas");
canvas.width = newWidth; canvas.height = newHeight;
log(canvas);
ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, newWidth, newHeight);
//log(ctx);
newDataUrl = canvas.toDataURL(imageType, imageArguments);
resolve(newDataUrl);
});
};
the use of it :
minifyImg(<--DATAURL_HERE-->,<--new width-->,<--type like image/jpeg-->,(data)=>{
console.log(data); // the new DATAURL
});
enjoy ;)
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
One way to do this is to pull your field into the rows section of the pivot table from the Filter section. Then group the values that you want to keep into a group, using the group option on the menu. After that is completed, drag your field back into the Filters section. The grouping will remain and you can check or uncheck one box to remove lots of values.
If you want to display at row=159220
row=159220
#To display in a table format
display(res.loc[row:row])
display(res.iloc[row:row+1])
#To display in print format
display(res.loc[row])
display(res.iloc[row])
I was trying to install docker-compose on "Ubuntu 16.04.5 LTS" but after installing it like this:
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
I was getting:
-bash: /usr/local/bin/docker-compose: Permission denied
and while I was using it with sudo I was getting:
sudo: docker-compose: command not found
So here's the steps that I took and solved my problem:
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
sudo chmod +x /usr/bin/docker-compose
If you want to select every element that has class attribute "myclass" use
$('#mydiv .myclass');
If you want to select only div elements that has class attribute "myclass" use
$("div#mydiv div.myclass");
find more about jquery selectors refer these articles
I usually use a helper class I once wrote for this task:
import java.util.zip.*;
import java.io.*;
public class ZipExample {
public static void main(String[] args){
ZipHelper zippy = new ZipHelper();
try {
zippy.zipDir("folderName","test.zip");
} catch(IOException e2) {
System.err.println(e2);
}
}
}
class ZipHelper
{
public void zipDir(String dirName, String nameZipFile) throws IOException {
ZipOutputStream zip = null;
FileOutputStream fW = null;
fW = new FileOutputStream(nameZipFile);
zip = new ZipOutputStream(fW);
addFolderToZip("", dirName, zip);
zip.close();
fW.close();
}
private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws IOException {
File folder = new File(srcFolder);
if (folder.list().length == 0) {
addFileToZip(path , srcFolder, zip, true);
}
else {
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip, false);
}
else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip, false);
}
}
}
}
private void addFileToZip(String path, String srcFile, ZipOutputStream zip, boolean flag) throws IOException {
File folder = new File(srcFile);
if (flag) {
zip.putNextEntry(new ZipEntry(path + "/" +folder.getName() + "/"));
}
else {
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
}
else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
}
}
Your code snippet,
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
actually checks if number is larger than both 10000 and 30000.
Assuming you want to check that the number is in the range 10000 - 30000, you could use the Python interval comparison:
if 10000 <= number <= 30000:
print ("you have to pay 5% taxes")
This Python feature is further described in the Python documentation.
Installed it using pip on Ubuntu 15.10 using a normal user, it was put in ~/.local/bin/virtualenvwrapper.sh
which I found by running:
$ find / -name virtualenvwrapper.sh 2>/dev/null
Your class doesn't have a __init__()
, so by the time it's instantiated, the attribute atoms
is not present. You'd have to do C.setdata('something')
so C.atoms
becomes available.
>>> C = Residues()
>>> C.atoms.append('thing')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'
>>> C.setdata('something')
>>> C.atoms.append('thing') # now it works
>>>
Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.
To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms
list you could add a constructor:
def __init__(self):
self.atoms = []
Debian:
cd /tmp/
wget https://deb.nodesource.com/setup_8.x
echo 'deb https://deb.nodesource.com/node_8.x stretch main' > /etc/apt/sources.list.d/nodesource.list
wget -qO - https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -
apt update
apt install nodejs
node -v
npm -v
Foreign keys are almost always "Allow Duplicates," which would make them unsuitable as Primary Keys.
Instead, find a field that uniquely identifies each record in the table, or add a new field (either an auto-incrementing integer or a GUID) to act as the primary key.
The only exception to this are tables with a one-to-one relationship, where the foreign key and primary key of the linked table are one and the same.
For set grouped style in ui itself:-Select the TableView then change the "style"(in attribute inspector)) from plain to Grouped.
There is a JSONObject constructor to turn a String into a JSONObject:
http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)
To change column data type there are change method and modify method
ALTER TABLE student_info CHANGE roll_no roll_no VARCHAR(255);
ALTER TABLE student_info MODIFY roll_no VARCHAR(255);
To change the field name also use the change method
ALTER TABLE student_info CHANGE roll_no identity_no VARCHAR(255);
You can Start the android Service by this command.
adb shell am startservice -n packageName/.ServiceClass
First I think you need to fix your lists, as the first node of a <ul>
must be a <li>
(stackoverflow ref). Once that is setup you can do this:
// note this array has outer scope
var phrases = [];
$('.phrase').each(function(){
// this is inner scope, in reference to the .phrase element
var phrase = '';
$(this).find('li').each(function(){
// cache jquery var
var current = $(this);
// check if our current li has children (sub elements)
// if it does, skip it
// ps, you can work with this by seeing if the first child
// is a UL with blank inside and odd your custom BLANK text
if(current.children().size() > 0) {return true;}
// add current text to our current phrase
phrase += current.text();
});
// now that our current phrase is completely build we add it to our outer array
phrases.push(phrase);
});
// note the comma in the alert shows separate phrases
alert(phrases);
Working jsfiddle.
One thing is if you get the .text()
of an upper level li
you will get all sub level text with it.
Keeping an array will allow for many multiple phrases to be extracted.
EDIT:
This should work better with an empty UL
with no LI
:
// outer scope
var phrases = [];
$('.phrase').each(function(){
// inner scope
var phrase = '';
$(this).find('li').each(function(){
// cache jquery object
var current = $(this);
// check for sub levels
if(current.children().size() > 0) {
// check is sublevel is just empty UL
var emptyULtest = current.children().eq(0);
if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){
phrase += ' -BLANK- '; //custom blank text
return true;
} else {
// else it is an actual sublevel with li's
return true;
}
}
// if it gets to here it is actual li
phrase += current.text();
});
phrases.push(phrase);
});
// note the comma to separate multiple phrases
alert(phrases);
The reason it is throwing that exception is because you have the argument rb
, which opens the file in binary mode. Change that to r
, which will by default open the file in text mode.
Your code:
import csv
ifile = open('sample.csv', "rb")
read = csv.reader(ifile)
for row in read :
print (row)
New code:
import csv
ifile = open('sample.csv', "r")
read = csv.reader(ifile)
for row in read :
print (row)
I don't think that it is possible. but you can do UITableView
(grouped) with 1 section and 1 empty cell and use it as a container for your UITextView
.
Mine was quite a unique case but this could help someone. On Android I tried to copy nano from my termux binary folder to /system/xbin. Placed all the library dependencies in /system/lib and got this error. The libncurses.so.6 file I copied from termux had it's TERMINFO file still pointed to /data/data/com.termux/files/usr/share/terminfo
View pointed path with command
strings path-to-libncurses.so | grep /terminfo
To fix either make the termux terminfo dir and subdirs readable and executable by the nano user or copy the terminfo folder somewhere else and use a hexeditor to modify the plain text path in the shared library file.
Link to zipped terminfo folder https://drive.google.com/file/d/1m1tfHgkGRehBGh1jPMK4EaTgQb9EyCG7/view?usp=drivesdk
You can use Array fill and map from Es6; just like some few people suggested in the answers they gave for this question. Below are some few examples:
Example-One: Array(10).fill(0).map((e,i)=>i+1)
Result-One: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Example-Two: Array(100/10).fill(0).map((e,i)=>(i*10)+10)
Result-Two:[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
I prefer this because I find it straight forward and easier.
You have to use the NotifyIcon control from System.Windows.Forms, or alternatively you can use the Notify Icon API provided by Windows API. WPF Provides no such equivalent, and it has been requested on Microsoft Connect several times.
I have code on GitHub which uses System.Windows.Forms
NotifyIcon Component from within a WPF application, the code can be viewed at https://github.com/wilson0x4d/Mubox/blob/master/Mubox.QuickLaunch/AppWindow.xaml.cs
Here are the summary bits:
Create a WPF Window with ShowInTaskbar=False, and which is loaded in a non-Visible State.
At class-level:
private System.Windows.Forms.NotifyIcon notifyIcon = null;
During OnInitialize():
notifyIcon = new System.Windows.Forms.NotifyIcon();
notifyIcon.Click += new EventHandler(notifyIcon_Click);
notifyIcon.DoubleClick += new EventHandler(notifyIcon_DoubleClick);
notifyIcon.Icon = IconHandles["QuickLaunch"];
During OnLoaded():
notifyIcon.Visible = true;
And for interaction (shown as notifyIcon.Click and DoubleClick above):
void notifyIcon_Click(object sender, EventArgs e)
{
ShowQuickLaunchMenu();
}
From here you can resume the use of WPF Controls and APIs such as context menus, pop-up windows, etc.
It's that simple. You don't exactly need a WPF Window to host to the component, it's just the most convenient way to introduce one into a WPF App (as a Window is generally the default entry point defined via App.xaml), likewise, you don't need a WPF Wrapper or 3rd party control, as the SWF component is guaranteed present in any .NET Framework installation which also has WPF support since it's part of the .NET Framework (which all current and future .NET Framework versions build upon.) To date, there is no indication from Microsoft that SWF support will be dropped from the .NET Framework anytime soon.
Hope that helps.
It's a little cheese that you have to use a pre-3.0 Framework Component to get a tray-icon, but understandably as Microsoft has explained it, there is no concept of a System Tray within the scope of WPF. WPF is a presentation technology, and Notification Icons are an Operating System (not a "Presentation") concept.
Since <input>
element displays only value of value attribute, we have to manipulate only it:
<input type="submit" class="btn fa-input" value=" Input">
I'm using 
entity here, which corresponds to the U+F043, the Font Awesome's 'tint' symbol.
Then we have to style it to use the font:
.fa-input {
font-family: FontAwesome, 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
Which will give us the tint symbol in Font Awesome and the other text in the appropriate font.
However, this control will not be pixel-perfect, so you might have to tweak it by yourself.
Quick fix. Create whole structure tr > td > button; then find button inside; attach event on it; end filtering of chain and at the and insert it into dom.
$("#myButton").click(function () {
var test = $('<tr><td><button>Test</button></td></tr>').find('button').click(function () {
alert('hi');
}).end();
$("#nodeAttributeHeader").attr('style', 'display: table-row;');
$("#addNodeTable tr:last").before(test);
});
This is a simple way of doing something.
@Override
public void onBackPressed() {
// do what you want to do when the "back" button is pressed.
startActivity(new Intent(Activity.this, MainActivity.class));
finish();
}
I think there might be more elaborate ways of going about it, but I like simplicity. For example, I used the template above to make the user sign out of the application AND THEN go back to another activity of my choosing.
When you do new Promise((resolve)...
the type inferred was Promise<{}>
because you should have used new Promise<number>((resolve)
.
It is interesting that this issue was only highlighted when the async
keyword was added. I would recommend reporting this issue to the TS team on GitHub.
There are many ways you can get around this issue. All the following functions have the same behavior:
const whatever1 = () => {
return new Promise<number>((resolve) => {
resolve(4);
});
};
const whatever2 = async () => {
return new Promise<number>((resolve) => {
resolve(4);
});
};
const whatever3 = async () => {
return await new Promise<number>((resolve) => {
resolve(4);
});
};
const whatever4 = async () => {
return Promise.resolve(4);
};
const whatever5 = async () => {
return await Promise.resolve(4);
};
const whatever6 = async () => Promise.resolve(4);
const whatever7 = async () => await Promise.resolve(4);
In your IDE you will be able to see that the inferred type for all these functions is () => Promise<number>
.
It depends on the output of file which I am not sure is standardized on all systems. Some JPEGs don't report the image size
import subprocess, re
image_size = list(map(int, re.findall('(\d+)x(\d+)', subprocess.getoutput("file" + filename))[-1]))
Set the values for each of the options
<select id="aioConceptName">
<option value="0">choose io</option>
<option value="1">roma</option>
<option value="2">totti</option>
</select>
$('#aioConceptName').val()
didn't work because .val()
returns the value
attribute. To have it work properly, the value
attributes must be set on each <option>
.
Now you can call $('#aioConceptName').val()
instead of all this :selected
voodoo being suggested by others.
I had the same problem with sql-dataadapter to update data and so on
the following is working for me fine
mydatgridview.Rows[x].Cells[x].Value="test"
mydatagridview.enabled = false
mydatagridview.enabled = true
also, you can fetch all data and count in the blade file. for example:
your code in the controller
$posts = Post::all();
return view('post', compact('posts'));
your code in the blade file.
{{ $posts->count() }}
finally, you can see the total of your posts.
Mi solution :
pw = "1321";
if (pw.length() < 16){
for(int x = pw.length() ; x < 16 ; x++){
pw += "*";
}
}
The output :
1321************
To know the package owning (or providing) an already installed file:
rpm -qf myfilename
First the mysqldump command is executed and the output generated is redirected using the pipe. The pipe is sending the standard output into the gzip command as standard input. Following the filename.gz, is the output redirection operator (>) which is going to continue redirecting the data until the last filename, which is where the data will be saved.
For example, this command will dump the database and run it through gzip and the data will finally land in three.gz
mysqldump -u user -pupasswd my-database | gzip > one.gz > two.gz > three.gz
$> ls -l
-rw-r--r-- 1 uname grp 0 Mar 9 00:37 one.gz
-rw-r--r-- 1 uname grp 1246 Mar 9 00:37 three.gz
-rw-r--r-- 1 uname grp 0 Mar 9 00:37 two.gz
My original answer is an example of redirecting the database dump to many compressed files (without double compressing). (Since I scanned the question and seriously missed - sorry about that)
This is an example of recompressing files:
mysqldump -u user -pupasswd my-database | gzip -c > one.gz; gzip -c one.gz > two.gz; gzip -c two.gz > three.gz
$> ls -l
-rw-r--r-- 1 uname grp 1246 Mar 9 00:44 one.gz
-rw-r--r-- 1 uname grp 1306 Mar 9 00:44 three.gz
-rw-r--r-- 1 uname grp 1276 Mar 9 00:44 two.gz
This is a good resource explaining I/O redirection: http://www.codecoffee.com/tipsforlinux/articles2/042.html
It's not pretty and it's not fast, but it works, it's a one-liner and it's LINQy:
List<string> a = text.Select((c, i) => new { Char = c, Index = i }).GroupBy(o => o.Index / 4).Select(g => new String(g.Select(o => o.Char).ToArray())).ToList();
With AppleScript:
display notification "Notification text" with title "Notification Title" subtitle "Notification sub-title" sound name "Submarine"
With terminal/bash and osascript
:
osascript -e 'display notification "Notification text" with title "Notification Title" subtitle "Notification sub-title" sound name "Submarine"'
Does not take the sub-heading nor the sound tough.
With AppleScript:
display alert "Alert title" message "Your message text line here."
With terminal/bash and osascript
:
osascript -e 'display alert "Alert title" message "Your message text line here."'
Add a line in bash for playing the sound after the alert line:
afplay /System/Library/Sounds/Hero.aiff
Add same line in AppleScript, letting shell script do the work:
do shell script ("afplay /System/Library/Sounds/Hero.aiff")
List of macOS built in sounds to choose from here.
Paraphrased from a handy article on terminal and applescript notifications.
This code works for me:
Dim script As String = "<script type=""text/javascript"">window.open('" & URL.ToString & "');</script>"
ClientScript.RegisterStartupScript(Me.GetType, "openWindow", script)
$out.='<option value="'.$key.'">'.$value["name"];
me funciono con esta
"<a href='javascript:void(0)' onclick='cargar_datos_cliente(\"$row->DSC_EST\")' class='button micro asignar margin-none'>Editar</a>";
Adding points to the accepted answer:
See the usage of IntentService within Android API. eg:
public class SimpleWakefulService extends IntentService {
public SimpleWakefulService() {
super("SimpleWakefulService");
}
@Override
protected void onHandleIntent(Intent intent) { ...}
To create an IntentService component for your app, define a class that extends IntentService, and within it, define a method that overrides onHandleIntent().
Also, see the source code of the IntentService, it's constructor and life cycle methods like onStartCommand...
@Override
public int More ...onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
Service together an AsyncTask is one of best approaches for many use cases where the payload is not huge. or just create a class extending IntentSerivce. From Android version 4.0 all network operations should be in background process otherwise the application compile/build fails. separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. For more discussion of this topic, see the blog post
from Android developers guide:
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent, in turn, using a worker thread, and stops itself when it runs out of work.
Design pattern used in IntentService
: This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
The IntentService class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface's responsiveness. Also, an IntentService isn't affected by most user interface lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask.
An IntentService has a few limitations:
It can't interact directly with your user interface. To put its results in the UI, you have to send them to an Activity. Work requests run sequentially. If an operation is running in an IntentService, and you send it another request, the request waits until the first operation is finished. An operation running on an IntentService can't be interrupted. However, in most cases
IntentService is the preferred way to simple background operations
**
Volley Library
There is the library called volley-library for developing android networking applications The source code is available for the public in GitHub.
The android official documentation for Best practices for Background jobs: helps better understand on intent service, thread, handler, service. and also Performing Network Operations
See https://polarssl.org/kb/cryptography/asn1-key-structures-in-der-and-pem (search the page for "BEGIN RSA PRIVATE KEY") (archive link for posterity, just in case).
BEGIN RSA PRIVATE KEY
is PKCS#1 and is just an RSA key. It is essentially just the key object from PKCS#8, but without the version or algorithm identifier in front. BEGIN PRIVATE KEY
is PKCS#8 and indicates that the key type is included in the key data itself. From the link:
The unencrypted PKCS#8 encoded data starts and ends with the tags:
-----BEGIN PRIVATE KEY----- BASE64 ENCODED DATA -----END PRIVATE KEY-----
Within the base64 encoded data the following DER structure is present:
PrivateKeyInfo ::= SEQUENCE { version Version, algorithm AlgorithmIdentifier, PrivateKey BIT STRING } AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY DEFINED BY algorithm OPTIONAL }
So for an RSA private key, the OID is 1.2.840.113549.1.1.1 and there is a RSAPrivateKey as the PrivateKey key data bitstring.
As opposed to BEGIN RSA PRIVATE KEY
, which always specifies an RSA key and therefore doesn't include a key type OID. BEGIN RSA PRIVATE KEY
is PKCS#1
:
RSA Private Key file (PKCS#1)
The RSA private key PEM file is specific for RSA keys.
It starts and ends with the tags:
-----BEGIN RSA PRIVATE KEY----- BASE64 ENCODED DATA -----END RSA PRIVATE KEY-----
Within the base64 encoded data the following DER structure is present:
RSAPrivateKey ::= SEQUENCE { version Version, modulus INTEGER, -- n publicExponent INTEGER, -- e privateExponent INTEGER, -- d prime1 INTEGER, -- p prime2 INTEGER, -- q exponent1 INTEGER, -- d mod (p-1) exponent2 INTEGER, -- d mod (q-1) coefficient INTEGER, -- (inverse of q) mod p otherPrimeInfos OtherPrimeInfos OPTIONAL }
Important (in Vue 4 and likely Vue 3+ as well!): I set VUE_APP_VAR but could NOT see it by console logging process and opening the env object. I could see it by logging or referencing process.env.VUE_APP_VAR. I'm not sure why this is but be aware that you have to access the variable directly!
Try out this
var str ="{ "name" : "user"}";
var jsonData = JSON.parse(str);
console.log(jsonData.name)
//Array Object
str ="[{ "name" : "user"},{ "name" : "user2"}]";
jsonData = JSON.parse(str);
console.log(jsonData[0].name)
Here's a fairly unconventional (but fast) approach: use fwrite
from data.table
to "paste" the columns together, and fread
to read it back in. For convenience, I've written the steps as a function called fpaste
:
fpaste <- function(dt, sep = ",") {
x <- tempfile()
fwrite(dt, file = x, sep = sep, col.names = FALSE)
fread(x, sep = "\n", header = FALSE)
}
Here's an example:
d <- data.frame(a = 1:3, b = c('a','b','c'), c = c('d','e','f'), d = c('g','h','i'))
cols = c("b", "c", "d")
fpaste(d[cols], "-")
# V1
# 1: a-d-g
# 2: b-e-h
# 3: c-f-i
How does it perform?
d2 <- d[sample(1:3,1e6,TRUE),]
library(microbenchmark)
microbenchmark(
docp = do.call(paste, c(d2[cols], sep="-")),
tidr = tidyr::unite_(d2, "x", cols, sep="-")$x,
docs = do.call(sprintf, c(d2[cols], '%s-%s-%s')),
appl = apply( d2[, cols ] , 1 , paste , collapse = "-" ),
fpaste = fpaste(d2[cols], "-")$V1,
dt2 = as.data.table(d2)[, x := Reduce(function(...) paste(..., sep = "-"), .SD), .SDcols = cols][],
times=10)
# Unit: milliseconds
# expr min lq mean median uq max neval
# docp 215.34536 217.22102 220.3603 221.44104 223.27224 225.0906 10
# tidr 215.19907 215.81210 220.7131 220.09636 225.32717 229.6822 10
# docs 281.16679 285.49786 289.4514 286.68738 290.17249 312.5484 10
# appl 2816.61899 3106.19944 3259.3924 3266.45186 3401.80291 3804.7263 10
# fpaste 88.57108 89.67795 101.1524 90.59217 91.76415 197.1555 10
# dt2 301.95508 310.79082 384.8247 316.29807 383.94993 874.4472 10
As Karthik mentioned, dct.keys()
will work but it will return all the keys in dict_keys
type not in list
type. So if you want all the keys in a list, then list(dct.keys())
will work.
struct Bool {
int true;
int false;
}
int main() {
/* bool is a variable of data type – bool*/
struct Bool bool;
/*below I’m accessing struct members through variable –bool*/
bool = {1,0};
print("Student Name is: %s", bool.true);
return 0;
}